I have been developing an automated deployment using Capistrano and using Vagrant as my test virtual server.
The thing is, I need the IP of Vagrant to \"ssh
I find that I do need the IP in order to configure /etc/hosts
on the host system to point at services on the fresh VM.
Here's a rough version of what I use to fetch the IP. Let Vagrant do its SSH magic and ask the VM for its address; tweak for your needs.
new_ip=$(vagrant ssh -c "ip address show eth0 | grep 'inet ' | sed -e 's/^.*inet //' -e 's/\/.*$//'")
I just found this in the Vagrant Docs. Looks like they consider it a valid approach:
This will automatically assign an IP address from the reserved address space. The IP address can be determined by using vagrant ssh to SSH into the machine and using the appropriate command line tool to find the IP, such as ifconfig.
I needed to know this to tell a user what to add to their host machine's host file. This works for me inside vagrant using just bash:
external_ip=$(cat /vagrant/config.yml | grep vagrant_ip | cut -d' ' -f2 | xargs)
echo -e "# Add this line to your host file:\n${external_ip} host.vagrant.vm"
In the terminal type:
ip addr show
I did at VagrantFile:
REMOTE_IP = %x{/usr/local/bin/vagrant ssh-config | /bin/grep -i HostName | /usr/bin/cut -d\' \' -f4}
run "ping #{REMOTE_IP}"
As you can see, I used the "%x{}" ruby function.
By default, a vagrant box doesn't have any ip address. In order to find the IP address, you simply assign the IP address in your Vagrantfile
then call vagrant reload
If you just need to access a vagrant machine from only the host machine, setting up a "private network" is all you need. Either uncomment the appropriate line in a default Vagrantfile
, or add this snippet. If you want your VM to appear at 172.30.1.5
it would be the following:
config.vm.network "private_network", ip: "172.30.1.5"
Learn more about private networks. https://www.vagrantup.com/docs/networking/private_network.html
If you need vagrant to be accessible outside your host machine, for instance for developing against a mobile device such as iOS or Android, you have to enable a public network you can use either static IP, such as 192.168.1.10
, or DHCP.
config.vm.network "public_network", ip: "192.168.1.10"
Learn more about configuring a public network https://www.vagrantup.com/docs/networking/public_network.html
run:
vagrant ssh-config > .ssh.config
and then in config/deploy.rb
role :web, "default"
role :app, "default"
set :use_sudo, true
set :user, 'root'
set :run_method, :sudo
# Must be set for the password prompt from git to work
default_run_options[:pty] = true
ssh_options[:forward_agent] = true
ssh_options[:config] = '.ssh.config'