From charlesreid1

When defining playbooks and hosts, it is useful to be able to deal with multiple hosts at once. This page covers basic group operations in Ansible.

Why groups?

Groups allow you to perform actions in bulk on different hosts. For example, you can define which servers are part of your production or testing environment, or you can define which of the servers in a given environment runs a database backend and which runs a web esrver frontend.

Default group: all

By default, the group all refers to all hosts listed in the host file. To run a command on all Ansible nodes (for example, date):

ansible all -a "date"

can also use pattern matching:

ansible '*' -a "date"

Ansible hosts file

The following ansible hosts file demonstrates an application of groups: labeling which machines are local vagrant machines, versus staging or production machines:

newhampshire.example.com
maryland.example.com
virginia.example.com
newyork.example.com
rhodeisland.example.com

redblue.example.com
orangered.example.com

[vagrant]
vagrant1 ansible_host=127.0.0.1 ansible_port=2222
vagrant2 ansible_host=127.0.0.1 ansible_port=2200
vagrant3 ansible_host=127.0.0.1 ansible_port=2201

More complex groupings

A more complex grouping example is given in the hosts file on the Ansible/Full Stack Playbook page.

In that scenario, Ansible was being used to deploy a web application that had a Django frontend, an http server, an Nginx load balancer, Celery task queue, RabbitMQ message queue (for celery backend), and Postgres (data store).

This was being deployed into 3 environments: vagrant (local testing), staging (testing), and production, with different configurations in each environment.

To organize this, the following hosts file was used:

[production]
delaware.example.com
georgia.example.com
maryland.example.com
newhampshire.example.com
newjersey.example.com
newyork.example.com
northcarolina.example.com
pennsylvania.example.com
rhodeisland.example.com
virginia.example.com

[staging]
redblue.example.com
orangered.example.com

[vagrant]
vagrant1 ansible_host=127.0.0.1 ansible_port=2222
vagrant2 ansible_host=127.0.0.1 ansible_port=2200
vagrant3 ansible_host=127.0.0.1 ansible_port=2201

[lb]
delaware.example.com

[web]
georgia.example.com
newhampshire.example.com
newjersey.example.com
redblue.example.com
vagrant1

[task]
newyork.example.com
northcarolina.example.com
maryland.example.com
redblue.example.com
vagrant2

[rabbitmq]
pennsylvania.example.com
orangered.example.com
vagrant3

[db]
rhodeisland.example.com
virginia.example.com
orangered.example.com
vagrant3

Groups of groups

Ansible allows defining groups composed of other groups.

To define which groups in the above example relate to Django (the web server and the task manager backend), we would say:

[django:children]
web
task

Pets vs Cattle

PetsVersusCattle.png


Flags