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

Quido picture Quido · Oct 29, 2015 · Viewed 8.7k times · Source

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

Answer

Carlos Guzman picture Carlos Guzman · Oct 29, 2015

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.