Set host name for Vagrant VM in Ansible

To test Ansible, I configured the Vagrant VM, which can be supplied with the vagrant provision specified

 config.vm.provision "ansible" do |ansible| ansible.playbook = "site.yml" end 

in the Vagrantfile . This works when I set hosts to all ,

 - hosts: all sudo: true roles: - common - ssl - webserver 

Alternatively file

 .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory 

which is generated by Vagrant itself, says

 default ansible_ssh_host=127.0.0.1 ansible_ssh_port=2222 

means the name of Vagrant VM is default . Hence,

 - hosts: default 

also does what i want. However, I would like to have a more specific name for the virtual machine (e.g. vagrant ).

Is there any way to change this name to something else?

+6
source share
3 answers

The trick is to define a virtual machine (here with two virtual machines production and staging ):

 config.vm.define "production" do |production| production.vm.hostname = "production.example.com" end config.vm.define "staging" do |staging| staging.vm.hostname = "staging.example.com" end 

Then the tramp generates the following inventory:

 production ansible_ssh_host=127.0.0.1 ansible_ssh_port=2222 staging ansible_ssh_host=127.0.0.1 ansible_ssh_port=2200 

See also this answer .

+8
source

To change only the inventory host name in .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory , use:

 config.vm.define "myvm" 

This will create the following:

 # Generated by Vagrant myvm ansible_ssh_host=127.0.0.1 ansible_ssh_port=2222 

Thus, the available inventory_hostname will become myvm .

If you want to also change the hostname of the machine, use:

 config.vm.define "myvm" do |myvm| myvm.vm.hostname = "myvm.example.com" end 
+3
source

You can read the inventory file from a stray document

If you want to change the name of the virtual machine, you can have something like

 Vagrant.configure("2") do |config| config.vm.define "host1" config.vm.provision "ansible" do |ansible| ansible.playbook = "site.yml" 

which will create the inventory file

 # Generated by Vagrant host1 ansible_ssh_host=... 

Note that the tramp also proposed a static inventory parameter that will allow you to write your own inventory file and link using the inventory_path option

+1
source

All Articles