有没有办法在 DHCP 分配的 Virtualbox 的 VagrantFile 中使用 IP 地址? [英] Is there a way to use the IP address in a VagrantFile that Virtualbox assigned by DHCP?

查看:19
本文介绍了有没有办法在 DHCP 分配的 Virtualbox 的 VagrantFile 中使用 IP 地址?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Vagrant 创建一个 VirtualBox 机器.在配置中,我需要知道 VirtualBox DHCP 分配的框的 IP 地址.有没有办法在 Vagrantfile 中使用分配的 IP 地址?

I am creating a VirtualBox machine with Vagrant. In the provisioning I need to know the IP address of the box that was assigned by the VirtualBox DHCP. Is there any way to use that assigned IP address in the Vagrantfile?

Vagrant.configure(2) do |config|
  # ... some more config

  config.vm.network "private_network", type: "dhcp"

  # ... some more config

  config.vm.provision "shell", inline: <<-SHELL
    sudo -i /vagrant/my_provisioning_script.sh <insert ip here>
  SHELL
end

推荐答案

你可以在 vagrant box 里面做一个 ifconfig 来获取你的 box 的 ips;应该是 eth0 中的 ip,但是由于您在配置中需要它并且您使用的是 shell,您可以这样做:

You can do an ifconfig inside the vagrant box to get the ips of your box; should be the ip in eth0, but since you need it on the provisioning and you are using shell you could do:

/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}'

在我的流浪箱中输出

10.0.2.15

所以你的命令可能是

  config.vm.provision "shell", inline: <<-SHELL
    sudo -i /vagrant/my_provisioning_script.sh $(/sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{ print $1}')
  SHELL

我用 ping 尝试了上面的方法.

I tried the above with ping.

如果需要,您也可以定义 ip,编辑您的 Vagrantfile 并添加:

Also you can define the ip if you want, edit your Vagrantfile and add:

config.vm.network "public_network", ip: "192.168.0.23"

这会将那个 ip 分配给你的盒子.如果您执行 ifconfig,它将列在 eth1 上.所以你可以在你的脚本中硬编码 ip.

this will assign that ip to your box. and if you do ifconfig it will be listed on eth1. So you could hardcode the ip on your script.

这篇关于有没有办法在 DHCP 分配的 Virtualbox 的 VagrantFile 中使用 IP 地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆