jstim
jstim

Reputation: 2432

Tell Vagrant the ip of the host machine

I am using a vagrant box as a development machine for a project with an odd dependency I can only seem to install on ubuntu.

I created my database and have my app code on my host computer, and I share them with the vagrant instance through the NFS file share and postgres config.

My issue is that, as I move my computer from work to home, the ip for my computer changes and my database.yml becomes invalid. To get my server and console working, I need to update the yaml file with the host's new ip address each time I join a new network.

Since the rails app is running on vagrant (even though it's files are located on my host machine), any attempt for me to grep the ip out of ifconfig will fail because it's looking at the VM and not the host box. So something like this doesn't work:

# database.yml
development:
  host: <%= `ifconfig en0 | grep "inet " | cut -d" " -f2` %>

Is there a config in the Vagrant file to pass this info through, or a way to create an ENV variable of the host ip that the ubuntu instance can read?

Upvotes: 37

Views: 32081

Answers (3)

Daniel Garmoshka
Daniel Garmoshka

Reputation: 6354

Not sure, if it will work for everybody, though all my virtual box machines see host machine by this "magic" ip:

10.0.2.2

Don't know if it's always static, though for me works and it's very convenient - I can use laptop at home, from office - having assigned different IPs to me by routers, but my VMs know the "trusty name" of their master 🐶

Upvotes: 62

Filipe Pina
Filipe Pina

Reputation: 2239

As an alternative to Matt's solution, you can also use private networks your Vagrantfile.

If you add a line such as:

config.vm.network "private_network", ip: "192.168.42.10"

Vagrant will add a second adapter to the virtual machine and hook it up to host-only adapter on that subnet.

This way you can then let database.yml simply point to 192.168.42.1 all the time (in this example).

Upvotes: 7

Matt Cooper
Matt Cooper

Reputation: 10840

According to this, you can reach the host through the VM's default gateway.

Running netstat -rn on the guest should give you the relevant info, on my machine changing your code above to the following looks like it would get things going for you:

# database.yml
development:
  host: <%= `netstat -rn | grep "^0.0.0.0 " | cut -d " " -f10` %>

Upvotes: 59

Related Questions