From charlesreid1

This page covers how to manage a static inventory file (a.k.a., hosts file, Ansible/Hosts) for Ansible, maintained by hand, if you are using Ansible with Vagrant.

Static vs dynamic inventory

Ansible/Vagrant/Static Inventory - static inventory requires the hosts file (containing the list of machines that Ansible is managing) be kept up to date by hand. This can be a burden if details are changing or if things are allocated automatically.

Ansible/Vagrant/Dynamic Inventory - dynamic inventory uses something like an API or a database to obtain information about the machines that Ansible is managing. This makes scaling and generalization much easier.

Managing a static inventory file: 1 Vagrant box

Edit playbooks/hosts and include details about each vagrant host.

Use the command vagrant ssh-config to get these details.

Example:

$ cat playbooks/hosts

myvagrantbox ansible_host=127.0.0.1 ansible_port=2222 ansible_user=vagrant ansible_private_key_file=.vagrant/machines/default/virtualbox/private_key

Your vagrant box should be up and running with the vagrant up command.

Managing static inventory file: Multiple Vagrant boxes

To configure multiple Vagrant boxes and keep them from stepping on each others' toes, edit the Vagrantfile and configure each machine before starting them up.

Here's an example 3-machine Vagrantfile:

VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|

  # Use the same key for each machine
  config.ssh.insert_key = false

  config.vm.define "vagrant1" do |vagrant1|
    vagrant1.vm.box = "ubuntu/xenial64"
    vagrant1.vm.network "forwarded_port", guest: 80, host: 8080
    vagrant1.vm.network "forwarded_port", guest: 443, host: 8443
  end
  config.vm.define "vagrant2" do |vagrant2|
    vagrant2.vm.box = "ubuntu/xenial64"
    vagrant2.vm.network "forwarded_port", guest: 80, host: 8081
    vagrant2.vm.network "forwarded_port", guest: 443, host: 8444
  end
  config.vm.define "vagrant3" do |vagrant3|
    vagrant3.vm.box = "ubuntu/xenial64"
    vagrant3.vm.network "forwarded_port", guest: 80, host: 8082
    vagrant3.vm.network "forwarded_port", guest: 443, host: 8445
  end
end

Note that without config.ssh.insert_key=false each machine would use its own SSH key, which would be a bit of a headache. With this directive, we can define a single SSH key in our ansible config file.

Flags