ruk·si

⚙️ Ansible
Playbooks

Updated at 2017-03-22 01:46

Playbooks are YAML files defining what needs to be applied to the targeted hosts.

Playbooks consist of a list of plays. Each play defines tasks to be done during that play where task should be an idempotent call to an Ansible module such as yum, pip or shell.

Playbooks usually have:

  • hosts defines which machines this playbook targets in your inventory in "host pattern" syntax
  • remote_user defines which user account to use to login to the machines
  • tasks has a list of module invocations that are applied. Each task has a human readable name that is shown in the playbook run output.
  • pre_tasks and post_tasks are like normal tasks, but pre are executed before tasks and post are executed after, duh.
  • handlers are tasks that are triggered by notify definitions, more about these later
---
- hosts: webserver
  remote_user: root
  tasks:
  - name: test connection
    ping:

If you use roles, you define that in the main playbook but then you usually omit the tasks section.

---
- hosts: webserver
  roles:
    - webserver

Tasks are executed in order, one at a time, against all machines matched by the host pattern, before moving on to the next task. Hosts with failed tasks are taken out of the rotation for the entire playbook.

The command and shell modules are the only modules that just take a list of arguments and don’t use the key=value form.

Task definitions may contain variables using {{ name }} syntax.

---
- hosts: webserver
  tasks:
    - name: create a virtual host file for {{ vhost }}
      template: src=somefile.j2 dest=/etc/httpd/conf.d/{{ vhost }}

Which can also be written as:

---
- hosts: webserver
  tasks:
    - name: create a virtual host file for {{ vhost }}
      template:
        src: somefile.j2
        dest: /etc/httpd/conf.d/{{ vhost }}

Sources