In order for Ansible to run playbooks and tasks, it needs to know which machines
to operate on. The standard way that Ansible achieves this is to use an
inventory file which lists the hosts and groups that playbooks will run
against. This inventory is a plain text ini file that lives at
/etc/ansible/hosts by default.

A dynamic inventory provides a way for Ansible to pull in inventory
information from other systems. This means that you do not need to manually
sync your local inventory with another source, rather you can invoke a script
that queries the source directly and makes the information available to
Ansible. Dynamic inventories are scripts that output JSON in a predefined
format that Ansible understands.

The Ansible project has an OpenStack dynamic inventory script available which
we can use to integrate Ansible with the Catalyst Cloud. This allows us
to use Ansible for configuration management of Catalyst Cloud instances
irrespective of what method has been used to create those instances.

Ansible supports replacing the standard inventory file with a dynamic inventory
script. Do this only if you wish the default Ansible inventory on your system
to be dynamically populated from your Catalyst Cloud project.

If you have replaced /etc/ansible/inventory then you don’t need to call ansible-playbook with the -i flag.

You will notice in the output above that the inventory script is passing
instance IDs as the hostname. If you would prefer to use instance names, you can
create a /etc/ansible/openstack.yml file with the following content:

ansible:use_hostnames:Trueexpand_hostvars:True

Note

The expand_hostvars option controls whether or not the inventory will make extra API calls to fill out additional information about each server.

With this file in place, the output will change to use instance names rather
than IDs:

You will notice that your playbook is configured to operate against all hosts
returned from the inventory script (set via hosts:all). If you would like to
operate on a subset of hosts, there are a number of options.

If you look at the JSON output again, you can see the information about your
instances is contained under the _meta key. The other top level keys of the
returned JSON object point to lists of instances. These keys relate to various
properties of your instances and are output by the dynamic inventory script
dynamically.

In addition to the automatic key creation, users can generate their own
groupings based on instance metadata. In the following example, you have added two
metadata items to each instance:

You can see a number of different groupings of instances are available, including
groupings based on the metadata you passed. Metadata with the key group is a
special case that will be translated directly into an Ansible host group of that
name.

Any of these groups may be used within a playbook. For example, let’s make use of
the group01 group to run our playbook against only example-instance-01: