Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 29 ยท Core Concepts

Playbooks and YAML Essentials

Write your first Ansible playbook: YAML rules and traps, plays, tasks, ansible-playbook, --check and --diff, and how to read the output and the play recap.

A playbook is a YAML file that lists what should be true on your servers. Where an ad-hoc command is one module call, a playbook is many of them in order, with names, grouped by the hosts they apply to, and saved in version control. Playbooks are the main thing you will write with Ansible.

Because a playbook is YAML, a little knowledge of YAML saves a lot of confusion: indentation mistakes, values that silently become booleans, and strings that need quotes. This lesson covers the YAML you need, the structure of plays and tasks, how to run a playbook safely with --check and --diff, and how to read the output. The playbooks are read-only examples for your own terminal; the stand-ins run a tiny play runner and show how YAML turns text into values.

YAML in five minutes

YAML describes three kinds of things: scalars (a string, number or boolean), lists and maps (key and value pairs). Structure comes from indentation with spaces, never tabs.

YAML
# A map with a scalar, a list and a nested map
name: web1
packages:
  - nginx
  - git
  - curl
limits:
  cpu: 2
  memory_mb: 2048
  • A list item starts with - . A map entry is key: value with a space after the colon.
  • Indent consistently; two spaces per level is the common style. Items that belong together must line up exactly.
  • # starts a comment. A document may start with ---.

Long text uses block scalars:

YAML
# Literal block: line breaks are kept
motd: |
  Welcome to the server.
  Authorized users only.

# Folded block: lines are joined into one paragraph
description: >
  This sentence is written over
  two lines but becomes one.

Quoting and the boolean trap

Most strings need no quotes, but some do. Quote a value when it:

  • starts with a special character such as {, [, *, &, !, %, @ or a backtick (a value starting with {{ is a Jinja expression, see Jinja2 Templates and Filters);
  • contains : (colon and space) or #;
  • would otherwise be read as another type.

That last reason causes the classic bugs. Ansible's YAML reader follows the older YAML 1.1 rules, so these plain words are not strings:

You write You get Fix
yes, on, true (any case) boolean true "yes" if you really want text
no, off, false boolean false "no"
1.10 number 1.1 "1.10"
0644 octal number "0644" for file modes
null, ~, empty null "null"

The famous example is a list of country codes where NO (Norway) turns into false. In Ansible the usual victims are version numbers (python: 3.10 becomes 3.1) and file modes. Quote file modes as strings, always: mode: "0644".

Plays and tasks

A playbook is a list of plays. Each play connects a group of hosts to a list of tasks:

YAML
---
- name: Configure web servers
  hosts: web
  become: true
  tasks:
    - name: Install nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true

    - name: Write the welcome page
      ansible.builtin.copy:
        content: "Hello from Ansible\n"
        dest: /var/www/html/index.html
        mode: "0644"

    - name: Make sure nginx is running and enabled
      ansible.builtin.service:
        name: nginx
        state: started
        enabled: true

Read it from the outside in:

  • The file is a list (note the - before name:). That one item is a play.
  • hosts: web picks hosts from the inventory with the same pattern language as before (Inventory).
  • become: true runs the tasks with privilege escalation.
  • tasks: is a list. Each task has a human-readable name, then one module with its arguments as a map.

Always give tasks a name. It appears in the output, so a good name is documentation: "Install nginx" is better than nothing and much better than reading raw module names in a failure.

A playbook can contain several plays, for example one for database servers and then one for web servers. They run in order, one play at a time, and each can target different hosts.

flowchart TD
    PB["Playbook file"] --> P1["Play 1<br/>hosts: db"]
    PB --> P2["Play 2<br/>hosts: web"]
    P1 --> T1["Task: install postgres"]
    P1 --> T2["Task: start postgres"]
    P2 --> T3["Task: install nginx"]
    P2 --> T4["Task: copy site config"]

A playbook holds plays; each play pairs hosts with tasks that run in order.

Running a playbook

Terminal
ansible-playbook -i inventory/hosts.ini site.yml

Useful options before you run for real:

Option What it does
--syntax-check Parse the file and stop; catches YAML and structure errors
--list-tasks Show the tasks that would run
--list-hosts Show the hosts that would be targeted
--check (-C) Dry run: report what would change, change nothing
--diff (-D) Show the actual differences for files and templates
--limit web1 (-l) Restrict to some of the hosts
-v, -vvv More detail

A careful habit is ansible-playbook site.yml --check --diff first, read the report, then run without --check.

Check mode is a prediction, not a guarantee. Modules that cannot know what a command would do (such as command and shell) are skipped, and later tasks that depend on earlier changes can report differently than in a real run. Treat --check as a very useful preview, not as proof.

Reading the output

A run prints a header for the play, one section per task and a final recap:

TEXT
PLAY [Configure web servers] ***********************************

TASK [Gathering Facts] *****************************************
ok: [web1.example.com]
ok: [web2.example.com]

TASK [Install nginx] *******************************************
changed: [web1.example.com]
ok: [web2.example.com]

TASK [Write the welcome page] **********************************
changed: [web1.example.com]
changed: [web2.example.com]

PLAY RECAP *****************************************************
web1.example.com : ok=3  changed=2  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
web2.example.com : ok=3  changed=1  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0
  • Gathering Facts is an automatic first task that collects information about each host (you can turn it off; see Variables, Facts and Precedence).
  • ok means the task ran and nothing needed changing. changed means it changed something. skipping (a condition was false), failed and unreachable explain themselves.
  • In the recap, ok includes the changed tasks. Read changed=0 failed=0 unreachable=0 on a second run as "the servers already match the playbook".

When a task fails, Ansible stops working on that host and leaves the other hosts running. Fix the cause and run the playbook again; thanks to idempotence, the tasks that succeeded do no harm the second time.

Stand-in: a tiny play runner

This program is a very small imitation of ansible-playbook. Tasks are plain JavaScript objects (the real tool reads them from YAML), three modules exist, and a task can run in check mode, where it reports what it would do without changing the pretend servers. Watch the three runs: a dry run, a real run and a second real run.

Node.js A tiny play runner with check mode

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In the dry run nothing changes on the pretend servers, yet the report shows what would change, and the command task is skipped because a program's effect cannot be predicted. The real run applies the changes, and the third run shows changed=1 only for the command task, which always counts as a change, while the idempotent modules say ok. That last point is a real-world lesson: a shell command that reports changed on every run makes recaps useless, which is why Modules and Idempotence teaches changed_when.

Stand-in: how YAML reads plain words

Ansible's YAML reader decides the type of every unquoted value. This stand-in applies the YAML 1.1 style rules from the table above, so you can see which of your values would surprise you. Quoted values always stay strings.

JS Which plain YAML values change type?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

3.10 turns into the number 3.1, but 3.12.1 stays text because it is not a valid number, and 0644 becomes 420 (octal), which is why modes belong in quotes. This is a simplification of the real rules, but it matches the traps you meet daily.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which line correctly sets a file mode in a playbook?

    Quoting keeps the value a string, so the module receives exactly 0644. An unquoted 0644 is read as an octal number and a bare 644 means something else.
  2. 2. In a playbook, what is the value of enabled when you write enabled: yes?

    Ansible's YAML follows 1.1 rules where yes, on and true (any case) are booleans. Quote it to keep text.
  3. 3. What is the correct relationship between a playbook, plays and tasks?

    The file is the playbook. Each play pairs a host pattern with tasks, and each task calls one module.
  4. 4. You want a preview of what a playbook would change, including file differences, without changing anything. Which options do you use?

    --check predicts changes without making them, and --diff shows file differences. Remember that check mode is a prediction, not a guarantee.
  5. 5. The PLAY RECAP shows ok=5 changed=2 failed=0. What does ok=5 include?

    In the recap, ok counts every successful task, and changed counts the subset of those that changed something.

Summary

  • A playbook is a YAML list of plays; each play pairs hosts with a list of named tasks, and each task calls one module.
  • YAML uses space indentation, - for lists and key: value for maps; | and > write multi-line text.
  • Quote anything that could be read as another type (yes, 1.10, 0644) or that starts with a special character.
  • ansible-playbook accepts --syntax-check, --list-tasks, --check, --diff and --limit for safe, targeted runs.
  • Output reports ok, changed, skipping, failed or unreachable per host, with a PLAY RECAP at the end.
  • A good second run shows changed=0, the sign of an idempotent playbook.

Next: Modules and Idempotence