Ansible Playbook Running Against Wrong Vagrant VM

I have an Ansible playbook which, when I run it, executes its tasks against the wrong Vagrant VM. Here’s how I built my VMs:

~/playbooks/vagrant/Vagrantfile

Vagrant.configure(2) do |config|
config.ssh.insert_key = false
config.vm.box = “vagrant_base” # Fresh debian/jessie64 image
config.vm.define “web” do |web|
web.vm.network “private_network”, ip: “192.168.2.100”
end
config.vm.define “db” do |db|
db.vm.network “private_network”, ip: “192.168.2.101”
end
config.vm.define “fs” do |fs|
fs.vm.network “private_network”, ip: “192.168.2.102”
end
end

I run the playbook with this command:

ansible-playbook -i inventories/vagrant site.yml

The playbook just calls playbooks for each of my servers:

~/playbooks/example/site.yml

I just noticed that if I only bring the file server VM up and run the ansible setup command, I get an SSH error saying, “data could not be sent to the remote host”. But if I bring the database VM up, the command against the file server runs but the ansible_hostname is “db00”, not “fs00” as I would expect. Is this ansible_hostname fact what Ansible looks at when it tries to identify what server to run the playbook against? That’s what it seems like. I think this may be related to the fact that I created the Vagrant VMs in one directory (playbooks/vagrant) while my actual Ansible playbooks reside in another (playbooks/example). I did this because I initially wrote my playbooks to run against real Debian servers. They run just fine against those servers. I’m only having problems running them against my Vagrant VMs which I built later.

One thing I’m confused about is ansible_hostname versus inventory_hostname. When should each of them be used?

By the way, I’m just using example.com as an example. It’s not my real domain name.

The problem was that I needed to use the inventory file that Vagrant creates in .vagrant/provisioners/ansible/inventory/vagrant_ansible_inventory instead of the inventory/vagrant file I had created. I contains the necessary Ansible directives.