ansible-playbook — format and function of an ansible playbook file
Ansible ships with ansible-playbook, a tool for running playbooks. Playbooks can represent frequent tasks, desired system configurations, or deployment processes.
Here’s what playbook.yml (above) will do.
The first pattern will select all hosts. The patterns are the same as supported by /usr/bin/ansible.
First, it will run all the modules specified in base.yml. Includes can be used to implement classes of things, and if you wanted, a playbook could consist of nothing but include files. This is an example of an include.
After processing base.yml, on each host we’ll write for a JSON file into /etc/ansible/setup on each remote system with the values max_clients and http_port.
Next, we’ll use a Jinja2 template locally residing at /srv/templates/httpd.j2 to write the Apache config file on each host, using the previous values in that setup file.
Next, We’ll ensure that apache is running if stopped.
The template task set up a notifier, which means if the configuration file actually changed, we have a named handler, in this case, restart apache to run. In this case, all the notifiers come from handlers.yml, though it’s also ok to express handlers directly in the main yaml file too. Using the include promotes reuse.
What does the handler say? If and only if the config file changed, note that we need to restart apache at the end of the run, otherwise, don’t bother because we already know it is running.
Playbooks are executed top down and can contain multiple references to patterns. For instance, a playbook could do something to all webservers, then do something to all database servers, then do something different to all webservers again.
For each pattern, the tasks in the tasks list are executed in order for all hosts in the host file matching the pattern.
For each task, a name/action pair describes what the task is and what ansible module to use to accomplish the task, along with any arguments. Additional fields like comment: can be added and will be ignored, so feel free to take notes in the file.
Most modules accept key=value format arguments.
Handlers are like tasks, but are conditionally executed. If a module reports a change, it can notify one or more handler by name. If notified, it will run only for hosts that changed.
If a host has a failure, the host will be ignored for the remainder of the playbook execution.