Can Multiple Vagrant VMs communicate by VM hostname?

Viewed 19410

I am managing multiple VMs with Vagrant. Networks are configured as private, ip addresses have been set and hostnames are assigned. As shown in the Vagrantfile below.

The VMs can communicate with each other via the IP address, but I would like to know how to allow VMs to communicate using their assigned hostname. I.e. How to make ping comtest2 work from comtest1?

Vagrantfile:

Vagrant.configure("2") do |config|

  config.vm.define "comtest1" do |comtest1|
    comtest1.vm.box = "precise32"
    comtest1.vm.hostname = "comtest1"
    comtest1.vm.network "private_network", ip: "192.168.10.21"
  end

  config.vm.define "comtest2" do |comtest2|
    comtest2.vm.box = "precise32"
    comtest2.vm.hostname = "comtest2"
    comtest2.vm.network "private_network", ip: "192.168.10.22"
  end

end
5 Answers

If the host resolves DNS correctly, then you can configure Virtualbox to use the host as the DNS resolver.

config.vm.provider :virtualbox do |vb|
  vb.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
end

See https://serverfault.com/a/506206/250071


We use a local Ansible task to automatically add the provisioned box to the host /etc/hosts file. It is a little awkward, but has been very robust.

- setup:
  gather_subset: [network]
- name: Add host mapping to local /etc/hosts
  delegate_to: 127.0.0.1
  lineinfile: dest=/etc/hosts regexp=".+{{ vm.hostname }}$" line="{{ ansible_all_ipv4_addresses|sort|last }} {{ vm.hostname }}"
Related