8

For testing Ansible, I've set up a Vagrant VM which can be provisioned with vagrant provision, given

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, the 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

meaning that the name of the Vagrant VM is default. Hence,

- hosts: default

also does what I want. However, I'd like to have a more specific name for the VM (like vagrant, for example).

Is there a way to change that name to something else?

Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249

3 Answers3

10

The trick is to define the VM (here with 2 VMs 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 vagrant 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.

Community
  • 1
  • 1
andrenarchy
  • 448
  • 3
  • 12
5

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

config.vm.define "myvm"

This will generate the following:

# Generated by Vagrant
myvm ansible_ssh_host=127.0.0.1 ansible_ssh_port=2222

Thus, ansible 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
user1338062
  • 11,939
  • 3
  • 73
  • 67
2

You can read The inventory file from the vagrant doc

If you want to change the name of the VM, you could have something like

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

which will produce the inventory file

# Generated by Vagrant

host1 ansible_ssh_host=...

Note that vagrant also proposed a static inventory option which will allow you to write your own inventory file and reference with the inventory_path option

Frederic Henri
  • 51,761
  • 10
  • 113
  • 139
  • This only only changes the `hostname` within the VM, not the contents of `.vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory` and hence not the name Ansible refers to. – Nico Schlömer Sep 09 '15 at 16:39