Video Transcript
The second element to work with Ansible, unless you are using the ad-hoc commands we will see later, is the “Playbooks.” Playbooks are simple YAML files that contain “plays.” A “play” includes “tasks,” and the tasks are used to invoke modules. Let’s try to understand this with an example. Here, the playbook’s name is name:
, and it has two different “plays.” One is targeted to the group of hosts master
and the second one to the group compute
. Each play contains a list of tasks
. The first task of the first play uses the module module_a
. Some modules require arguments or options. In this example, a_argument
is an option used for the module module_a
.
Now let’s see a real playbook. In this example, you have one play, targeted to the master, and two different tasks. The first one uses the module service
with the arguments name
, state
and enabled
. This task is meant to enable and start the system service httpd. The second task uses the same service
module, but this time instead of enabling and starting one service, it is meant to enable and start three different services: httpd, named, and cobblerd. We use the keyword with_items
to iterate over the three services.
The name in each task is essential as it will let you debug your playbook easily. Let’s watch an example:
We will use the following inventory, see that localhost is part of the master group. Our playbook is targeted at the master group. To run it, we execute ansible-playbook -i inventory simple.yml
and press enter. We can see it finished successfully; This playbook started three services: httpd, named, and cobblerd. The ok=0
means all three parts of the task were done, and changed=0
means it did not start the services because they were already running. But let’s try this again, disabling one of the services: the httpd.
As you can see, this time, there is one change, meaning it did change something; checking the status of the httpd service, we can see Ansible started it.
In summary, Ansible does all the hard work of getting your systems to the desired state regardless of the state they are currently in. Playbooks make your deployments reliable and consistent, and you can write and maintain them as if they were source code, meaning all the developing strategies apply, e.g., the use of git, etc.
So far, we have only used the module service
. However, there are over a thousand modules provided by Ansible to automate every part of the environment. They are like plugins; you can develop your modules. They are standalone and written mostly in Python, but you can use other scripting languages. The main philosophy behind the modules is idempotency, meaning that even if an operation is repeated multiple times, it should always place the system into the same state. Here, you can see other modules, for example, file and copy. For more modules, visit the Ansible website.