How to use more than one inventory file in a playbook in one single command

If you want to run a playbook in more than one inventory file in one command you just need to put every inventory file you want inside a directory and then run:

ansible-playbook -i <inventory_file_directory> <playbook>

For example:

ansible-playbook -i inventory/rackspace_prod/ update_config.yml

So you can easily run a playbook and work with all servers that you need no matter in which environment file they are.

Let’s go a little deeper in the example above because you could think: why not create a bigger inventory file with everything inside it?

Imagine that you have one static inventory file (static) and a dynamic inventory file. For example Rackspace dynamic inventory file (rax.py). In both environments you have a group name called webservers because you use Rackspace Cloud Servers to scale up and down your static webservers.

If you want to operate all your webservers (static and dynamic servers) you could run the playbook twice:

ansible webservers -i inventory/static -m ping
ansible webservers -i inventory/rax.py -m ping

But you can create a directory called rackspace_prod and put there both inventory files and then run:

ansible webservers -i inventory/rackspace_prod/ -m ping

I normally use this feature to update configuration files like in apaches, loadbalancers or /etc/hosts file.

For example you can update haproxy configuration with your static and dynamic webservers by using a template file:

[...]
backend my_backend
option httpchk
cookie JSESSIONID prefix nocache
 balance roundrobin
{% for host in groups['webservers'] %}
 server {{ hostvars[host]['ansible_hostname'] }} {{ hostvars[host]['ansible_eth1']['ipv4']['address'] }}:80 check  {{ hostvars[host]['ansible_hostname'] }}
 {% endfor %}
[...]
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s