Intro to Playbooks

About Playbooks

Playbooks are a completely different way to use ansible than in adhoc task execution mode, and areparticularly powerful.

Simply put, playbooks are the basis for a really simple configuration management and multi-machine deployment system,unlike any that already exist, and one that is very well suited to deploying complex applications.

Playbooks can declare configurations, but they can also orchestrate steps ofany manual ordered process, even as different steps must bounce back and forthbetween sets of machines in particular orders. They can launch taskssynchronously or asynchronously.

While you might run the main /usr/bin/ansible program for ad-hoctasks, playbooks are more likely to be kept in source control and usedto push out your configuration or assure the configurations of yourremote systems are in spec.

There are also some full sets of playbooks illustrating a lot of these techniques in theansible-examples repository. We’d recommendlooking at these in another tab as you go along.

There are also many jumping off points after you learn playbooks, so hop back to the documentationindex after you’re done with this section.

Playbook Language Example

Playbooks are expressed in YAML format (see YAML Syntax) and have a minimum of syntax, which intentionallytries to not be a programming language or script, but rather a model of a configuration or a process.

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 bythings ansible calls tasks. At a basic level, a task is nothing more than a callto an ansible module (see Working With Modules).

By composing a playbook of multiple ‘plays’, it is possible toorchestrate multi-machine deployments, running certain steps on allmachines in the webservers group, then certain steps on the databaseserver group, then more commands back on the webservers group, etc.

“plays” are more or less a sports analogy. You can have quite a lot of plays that affect your systemsto do different things. It’s not as if you were just defining one particular state or model, and youcan run different plays at different times.

For starters, here’s a playbook that contains just one play:

  1. ---
  2. - hosts: webservers
  3. vars:
  4. http_port: 80
  5. max_clients: 200
  6. remote_user: root
  7. tasks:
  8. - name: ensure apache is at the latest version
  9. yum:
  10. name: httpd
  11. state: latest
  12. - name: write the apache config file
  13. template:
  14. src: /srv/httpd.j2
  15. dest: /etc/httpd.conf
  16. notify:
  17. - restart apache
  18. - name: ensure apache is running
  19. service:
  20. name: httpd
  21. state: started
  22. handlers:
  23. - name: restart apache
  24. service:
  25. name: httpd
  26. state: restarted

Playbooks can contain multiple plays. You may have a playbook that targets firstthe web servers, and then the database servers. For example:

  1. ---
  2. - hosts: webservers
  3. remote_user: root
  4.  
  5. tasks:
  6. - name: ensure apache is at the latest version
  7. yum:
  8. name: httpd
  9. state: latest
  10. - name: write the apache config file
  11. template:
  12. src: /srv/httpd.j2
  13. dest: /etc/httpd.conf
  14.  
  15. - hosts: databases
  16. remote_user: root
  17.  
  18. tasks:
  19. - name: ensure postgresql is at the latest version
  20. yum:
  21. name: postgresql
  22. state: latest
  23. - name: ensure that postgresql is started
  24. service:
  25. name: postgresql
  26. state: started

You can use this method to switch between the host group you’re targeting,the username logging into the remote servers, whether to sudo or not, and soforth. Plays, like tasks, run in the order specified in the playbook: top tobottom.

Below, we’ll break down what the various features of the playbook language are.

Basics

Hosts and Users

For each play in a playbook, you get to choose which machines in your infrastructureto 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 Working with Patternsdocumentation. The remote_user is just the name of the user account:

  1. ---
  2. - hosts: webservers
  3. remote_user: root

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:

  1. ---
  2. - hosts: webservers
  3. remote_user: root
  4. tasks:
  5. - name: test connection
  6. ping:
  7. remote_user: yourname

Support for running things as another user is also available (see Understanding Privilege Escalation):

  1. ---
  2. - hosts: webservers
  3. remote_user: yourname
  4. become: yes

You can also use keyword become on a particular task instead of the whole play:

  1. ---
  2. - hosts: webservers
  3. remote_user: yourname
  4. tasks:
  5. - service:
  6. name: nginx
  7. state: started
  8. become: yes
  9. become_method: sudo

You can also login as you, and then become a user different than root:

  1. ---
  2. - hosts: webservers
  3. remote_user: yourname
  4. become: yes
  5. become_user: postgres

You can also use other privilege escalation methods, like su:

  1. ---
  2. - hosts: webservers
  3. remote_user: yourname
  4. become: yes
  5. become_method: su

If you need to specify a password to sudo, run ansible-playbook with —ask-become-pass orwhen using the old sudo syntax —ask-sudo-pass (-K). If you run a become playbook and theplaybook seems to hang, it’s probably stuck at the privilege escalation prompt.Just Control-C to kill it and run it again adding the appropriate password.

Important

When using becomeuser to a user other than root, the modulearguments are briefly written into a random tempfile in /tmp.These are deleted immediately after the command is executed. Thisonly occurs when changing privileges from a user like ‘bob’ to ‘timmy’,not when going from ‘bob’ to ‘root’, or logging in directly as ‘bob’ or‘root’. If it concerns you that this data is briefly readable(not writable), avoid transferring unencrypted passwords with_become_user set. In other cases, /tmp is not used and this doesnot come into play. Ansible also takes care to not log passwordparameters.

New in version 2.4.

You can also control the order in which hosts are run. The default is to follow the order supplied by the inventory:

  1. - hosts: all
  2. order: sorted
  3. gather_facts: False
  4. tasks:
  5. - debug:
  6. var: inventory_hostname

Possible values for order are:

  • inventory:
  • The default. The order is ‘as provided’ by the inventory
  • reverse_inventory:
  • As the name implies, this reverses the order ‘as provided’ by the inventory
  • sorted:
  • Hosts are alphabetically sorted by name
  • reverse_sorted:
  • Hosts are sorted by name in reverse alphabetical order
  • shuffle:
  • Hosts are randomly ordered each run

Tasks list

Each play contains a list of tasks. Tasks are executed in order, oneat 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 mapa selection of hosts to tasks.

When running the playbook, which runs top to bottom, hosts with failed tasks aretaken 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 timesin a sequence should have the same effect as running it just once. Oneway to achieve idempotency is to have a module check whether its desiredfinal state has already been achieved, and if that state has been achieved,to exit without performing any actions. If all the modules a playbook usesare idempotent, then the playbook itself is likely to be idempotent, sore-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 likechmod or setsebool, etc. Though there is a creates flag available which canbe used to make these modules also idempotent.

Every task should have a name, which is included in the output fromrunning the playbook. This is human readable output, and so it isuseful to provide good descriptions of each task step. If the nameis not provided though, the string fed to ‘action’ will be used foroutput.

Tasks can be declared using the legacy action: module options format, butit is recommended that you use the more conventional module: options format.This recommended format is used throughout the documentation, but you mayencounter 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:

  1. tasks:
  2. - name: make sure apache is running
  3. service:
  4. name: httpd
  5. state: started

The command and shell modules are the only modules that just take a listof arguments and don’t use the key=value form. This makesthem work as simply as you would expect:

  1. tasks:
  2. - name: enable selinux
  3. command: /sbin/setenforce 1

The command and shell module care about return codes, so if you have a commandwhose successful exit code is not zero, you may wish to do this:

  1. tasks:
  2. - name: run this command and ignore the result
  3. shell: /usr/bin/somecommand || /bin/true

Or this:

  1. tasks:
  2. - name: run this command and ignore the result
  3. shell: /usr/bin/somecommand
  4. ignore_errors: True

If the action line is getting too long for comfort you can break it ona space and indent any continuation lines:

  1. tasks:
  2. - name: Copy ansible inventory file to client
  3. copy: src=/etc/ansible/hosts dest=/etc/ansible/hosts
  4. owner=root group=root mode=0644

Variables can be used in action lines. Suppose you defineda variable called vhost in the vars section, you could do this:

  1. tasks:
  2. - name: create a virtual host file for {{ vhost }}
  3. template:
  4. src: somefile.j2
  5. dest: /etc/httpd/conf.d/{{ vhost }}

Those same variables are usable in templates, which we’ll get to later.

Now in a very basic playbook all the tasks will be listed directly in that play, though it will usuallymake more sense to break up tasks as described in Creating Reusable Playbooks.

Action Shorthand

New in version 0.8.

Ansible prefers listing modules like this:

  1. template:
  2. src: templates/foo.j2
  3. dest: /etc/foo.conf

Early versions of Ansible used the following format, which still works:

  1. action: template src=templates/foo.j2 dest=/etc/foo.conf

Handlers: Running Operations On Change

As we’ve mentioned, modules should be idempotent and can relay whenthey have made a change on the remote system. Playbooks recognize this andhave a basic event system that can be used to respond to change.

These ‘notify’ actions are triggered at the end of each block of tasks in a play, and will only betriggered once even if notified by multiple different tasks.

For instance, multiple resources may indicatethat apache needs to be restarted because they have changed a config file,but apache will only be bounced once to avoid unnecessary restarts.

Here’s an example of restarting two services when the contents of a filechange, but only if the file changes:

  1. - name: template configuration file
  2. template:
  3. src: template.j2
  4. dest: /etc/foo.conf
  5. notify:
  6. - restart memcached
  7. - restart apache

The things listed in the notify section of a task are calledhandlers.

Handlers are lists of tasks, not really any different from regulartasks, that are referenced by a globally unique name, and are notifiedby notifiers. If nothing notifies a handler, it will notrun. Regardless of how many tasks notify a handler, it will run onlyonce, after all of the tasks complete in a particular play.

Here’s an example handlers section:

  1. handlers:
  2. - name: restart memcached
  3. service:
  4. name: memcached
  5. state: restarted
  6. - name: restart apache
  7. service:
  8. name: apache
  9. state: restarted

As of Ansible 2.2, handlers can also “listen” to generic topics, and tasks can notify those topics as follows:

  1. handlers:
  2. - name: restart memcached
  3. service:
  4. name: memcached
  5. state: restarted
  6. listen: "restart web services"
  7. - name: restart apache
  8. service:
  9. name: apache
  10. state:restarted
  11. listen: "restart web services"
  12.  
  13. tasks:
  14. - name: restart everything
  15. command: echo "this task will restart the web services"
  16. notify: "restart web services"

This use makes it much easier to trigger multiple handlers. It also decouples handlers from their names,making it easier to share handlers among playbooks and roles (especially when using 3rd party roles froma shared source like Galaxy).

Note

  • Notify handlers are always run in the same order they are defined, not in the order listed in the notify-statement. This is also the case for handlers using listen.
  • Handler names and listen topics live in a global namespace.
  • If two handler tasks have the same name, only one will run.*
  • You cannot notify a handler that is defined inside of an include. As of Ansible 2.1, this does work, however the include must be static.

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.

If you ever want to flush all the handler commands immediately you can do this:

  1. tasks:
  2. - shell: some tasks go here
  3. - meta: flush_handlers
  4. - shell: some other tasks

In the above example any queued up handlers would be processed early when the metastatement was reached. This is a bit of a niche case but can come in handy fromtime to time.

Executing A 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:

  1. 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, insteadof 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 thenrun 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 theplaybook 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 targetedand how they performed. General failures and fatal “unreachable” communication attempts arekept 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.

To see what hosts would be affected by a playbook before you run it, youcan do this:

  1. ansible-playbook playbook.yml --list-hosts

See also