A Play is a list of tasks and roles that should be run. A Play can also define vars that should be used for that play. A Playbook is a list of plays. It can contain a single play, or many.
The goal of a play is to map a group of hosts to some well defined roles, represented by things ansible calls tasks. At a basic level, a task is nothing more than a call to an ansible module (see About Modules).
“plays” are more or less a sports analogy. You can have quite a lot of plays that affect your systems to do different things. It’s not as if you were just defining one particular state or model, and you can run different plays at different times.
For each play in a playbook, you get to choose which machines in your infrastructure to target and what remote user to complete the steps (called tasks) as.
The hosts line is a list of one or more groups or host patterns, separated by colons, as described in the Patterns documentation. The remote_user is just the name of the user account:
---
- hosts: webservers
remote_user: root
or each play in a playbook, you get to choose which machines in your infrastructure to target and what remote user to complete the steps (called tasks) as.
At a basic level, playbooks can be used to manage
configurations of and deployments to remote machines. At a more advanced level,
they can sequence multi-tier rollouts involving rolling updates, and can
delegate actions to other hosts, interacting with monitoring servers and load
balancers along the way.
While there’s a lot of information here, there’s no need to learn everything at once. You can start small and pick up more features over time as you need them.
A playbook is structured like so:
---
- name: play 1
hosts: all
become: true
pre_tasks:
- name: do something before roles
debug: msg="this is run before a role"
roles:
- install_role
- name: play 2
hosts: group2
roles:
- config_role
Playbook Language Example
Playbooks are expressed in YAML format.
The hosts line is a list of one or more groups or host
patterns, separated by colons. The
remote_user is just the name of the user account:
'
How Play executes
How Play executes
Each play contains a list of tasks. Tasks are executed
in order, one at a time, against all machines matched by the host pattern,
before moving on to the next task. It is important to understand that, within a
play, all hosts are going to get the same task directives. It is the purpose of
a play to map a selection of hosts to tasks.
When running the playbook, which runs top to bottom, hosts with failed tasks are taken out of the rotation for the entire playbook. If things fail, simply correct the playbook file and rerun.
The goal of each task is to execute a module, with very specific arguments. Variables, as mentioned above, can be used in arguments to modules.
Modules should be idempotent, that is, running a module multiple times in a sequence should have the same effect as running it just once. One way to achieve idempotency is to have a module check whether its desired final state has already been achieved, and if that state has been achieved, to exit without performing any actions. If all the modules a playbook uses are idempotent, then the playbook itself is likely to be idempotent, so re-running the playbook should be safe.
The command and shell modules will typically rerun the same command again, which is totally ok if the command is something like chmod or setsebool, etc. Though there is a creates flag available which can be used to make these modules also idempotent.
Every task should have a name, which is included in the output from running the playbook. This is human readable output, and so it is useful to provide good descriptions of each task step. If the name is not provided though, the string fed to ‘action’ will be used for output.
Tasks can be declared using the legacy action: module options format, but it is recommended that you use the more conventional module: options format. This recommended format is used throughout the documentation, but you may encounter the older format in some playbooks.
Here is what a basic task looks like. As with most modules, the service module takes key=value arguments:
tasks:
- name: make
sure apache is running
service:
name=httpd state=started
The command and shell modules are the only modules that just take a list of arguments and don’t use the key=value form. This makes them work as simply as you would expect:
tasks:
- name: enable
selinux
command:
/sbin/setenforce 1
The command and shell module care about return codes, so if you have a command whose successful exit code is not zero, you may wish to do this:
tasks:
- name: run
this command and ignore the result
shell:
/usr/bin/somecommand || /bin/true
Or this:
tasks:
- name: run
this command and ignore the result
shell:
/usr/bin/somecommand
ignore_errors: True
If the action line is getting too long for comfort you can break it on a space and indent any continuation lines:
tasks:
- name: Copy
ansible inventory file to client
copy:
src=/etc/ansible/hosts dest=/etc/ansible/hosts
owner=root group=root mode=0644
Variables can be used in action lines. Suppose you defined a variable called vhost in the vars section, you could do this:
tasks:
- name: create
a virtual host file for {{ vhost }}
template:
src=somefile.j2 dest=/etc/httpd/conf.d/{{ vhost }}
Those same variables are usable in templates, which we’ll get to later.
Note : The remote_user parameter was formerly called just user. It was renamed in Ansible 1.4 to make it more distinguishable from the user module (used to create users on remote systems).
Remote users can also be defined per task:
---
- hosts: webservers
remote_user:
root
tasks:
- name: test
connection
ping:
remote_user: yourname
YAML Basics
Every YAML file starts with a list. Each item in the list is a list of key/value pairs, commonly called a “hash” or a “dictionary”. So, we need to know how to write lists and dictionaries in YAML.
All YAML files (regardless of their association with Ansible or not) can optionally begin with --- and end with .... This is part of the YAML format and indicates the start and end of a document.
All members of a list are lines beginning at the same indentation level starting with a "- " (a dash and a space):
---
# A list of tasty fruits
fruits:
- Apple
- Orange
- Strawberry
- Mango
...
A dictionary is represented in a simple key: value
form (the colon must be followed by a space):
# An employee record
martin:
name: Martin
D'vloper
job:
Developer
skill: Elite
Ansible doesn’t really use these too much, but you can also specify a boolean value (true/false) in several forms:
create_key: yes
needs_agent: no
knows_oop: True
likes_emacs: TRUE
uses_cvs: false
3) Values can span multiple lines using | or >. Spanning multiple lines using a | will include the newlines. Using a > will ignore newlines; it’s used to make what would otherwise be a very long line easier to read and edit. In either case the indentation will be ignored.
Examples are:
include_newlines: |
exactly as you see
will
appear these three
lines of poetry
ignore_newlines: >
this
is really a
single line of text
despite appearances
4) Dictionaries and lists can also be represented in
an abbreviated form if you really want to:
---
martin: {name: Martin D'vloper, job: Developer, skill:
Elite}
fruits: ['Apple', 'Orange', 'Strawberry', 'Mango']
WHAT IS HANDLERS
The things listed in the notify section of a task are
called handlers.
Handlers are lists of tasks, not really any different
from regular tasks, that are referenced by a globally unique name, and are
notified by notifiers. If nothing notifies a handler, it will not run.
Regardless of how many tasks notify a handler, it will run only once, after all
of the tasks complete in a particular play.
Here’s an example handlers section:
Each playbook is composed of one or more ‘plays’ in a list.
The goal of a play is to map a group of hosts to some well defined roles, represented by things ansible calls tasks. At a basic level, a task is nothing more than a call to an ansible module (see About Modules).
Roles are described later on, but it’s worthwhile to point out that:
handlers notified within pre_tasks, tasks, and
post_tasks sections are automatically flushed in the end of section where they
were notified;
handlers notified within roles section are
automatically flushed in the end of tasks section, but before any tasks
handlers.
HOW TO RUN PLAYBOOK
Now that you’ve learned playbook syntax, how do you
run a playbook? It’s simple. Let’s run a playbook using a parallelism level of
10:
ansible-playbook playbook.yml -f 10
Ansible-Pull
Should you want to invert the architecture of Ansible, so that nodes check in to a central location, instead of pushing configuration out to them, you can.
The ansible-pull is a small script that will checkout a repo of configuration instructions from git, and then run ansible-playbook against that content.
Assuming you load balance your checkout location, ansible-pull scales essentially infinitely.
Run ansible-pull --help for details.
There’s also a clever playbook available to configure ansible-pull via a crontab from push mode.
Tips and Tricks
To check the syntax of a playbook, use ansible-playbook with the --syntax-check flag. This will run the playbook file through the parser to ensure its included files, roles, etc. have no syntax problems.
Look at the bottom of the playbook execution for a summary of the nodes that were targeted and how they performed. General failures and fatal “unreachable” communication attempts are kept separate in the counts.
If you ever want to see detailed output from successful modules as well as unsuccessful ones, use the --verbose flag. This is available in Ansible 0.5 and later.
Ansible playbook output is vastly upgraded if the cowsay package is installed. Try it!
To see what hosts would be affected by a playbook before you run it, you can do this:
ansible-playbook playbook.yml --list-hosts
Task versus Play includes
Tasks and plays both use the include keyword, but implement the keyword differently. The difference between them is determined by their positioning and content. If the include is inside a play it can only be a ‘task’ include and include a list of tasks; if it is at the top level, it can only include plays. For example:
# this is a 'play' include
- include: intro_example.yml
- name: another play
hosts: all
tasks:
- debug:
msg=hello
# this is a
'task' include
- include:
stuff.yml
A task include file simply contains a flat list of tasks, like so:
---
# possibly saved as tasks/foo.yml
- name: placeholder foo
command:
/bin/foo
- name: placeholder bar
command:
/bin/bar
Include directives look like this, and can be mixed in
with regular tasks in a playbook:
tasks:
- include:
tasks/foo.yml
You can also pass variables into includes. We call this a ‘parameterized include’.
For instance, to deploy to multiple wordpress instances, I could encapsulate all of my wordpress tasks in a single wordpress.yml file, and use it like so:
tasks:
- include:
wordpress.yml wp_user=timmy
- include:
wordpress.yml wp_user=alice
- include:
wordpress.yml wp_user=bob
A Role is an organizational unit for tasks, vars, files, etc. Instead of having to list all of your tasks for a play directly in the playbook, you can reference a role, which contains tasks, vars, files, templates, and handlers in one nice, portable package.