Is there a way to use the IP address in a VagrantFile that Virtualbox assigned by DHCP?

元气小坏坏 提交于 2019-12-11 14:27:56

问题


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

回答1:


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}'

In my vagrant box this outputs

10.0.2.15

so your command could be

  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

I tried the above with ping.

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

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

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.



来源:https://stackoverflow.com/questions/33409641/is-there-a-way-to-use-the-ip-address-in-a-vagrantfile-that-virtualbox-assigned-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!