At the end of Module 2 you returned the Aurora Store servers to their clean state because nothing you had done with ad hoc commands was saved in the repository. Playbooks solve exactly that problem: they are YAML files in which you describe, step by step, the state your servers should end up in. They live in aurora-infra, are versioned with Git, are reviewed like any other code and can be run a thousand times with the same result. In this lesson you will understand what a playbook is and why it's the natural way to work with Ansible, you will get to know its hierarchy (playbook → plays → tasks → modules), you will write and run a short first playbook for Aurora and you will learn to read its output. The details of YAML, the complete web server playbook and the full anatomy of a playbook come in the following lessons.
Contents
- From ad hoc commands to code
- What a playbook is
- The hierarchy: playbook, plays, tasks and modules
- A first look: Aurora's
common.ymlplaybook - Running a playbook with
ansible-playbook - Reading the output and the
PLAY RECAP - Playbooks, ad hoc commands and scripts
- Where playbooks live in
aurora-infra
- From ad hoc commands to code
In Lesson 2.4 you installed htop, and in Lesson 2.6 you set the time zone, with two commands:
ansible aurora -m ansible.builtin.apt -a 'name=htop state=present update_cache=true cache_valid_time=3600' -b
ansible aurora -m community.general.timezone -a 'name={{ aurora_timezone }}' -bThey worked, but they have several problems when it comes to managing real infrastructure:
- They leave no trace: if a colleague joins tomorrow, there's no way to know what was done or in what order, short of digging through your terminal history.
- They can't be reviewed: nobody can approve a change before it's applied, the way it's done with application code.
- They can't be reliably repeated: to rebuild
web2you would have to remember every command, with every parameter, in the right order. - They don't scale: ten commands are manageable; two hundred are not.
The solution is the central idea of infrastructure as code (Lesson 1.1): write the desired state in files, store them in Git and let a tool apply them. In Ansible, those files are playbooks.
| Need | With ad hoc commands | With playbooks |
|---|---|---|
| Know what was configured | Terminal history (if it exists) | A file in the repository |
| Know who changed something and when | Impossible | git log, git blame |
| Review a change before applying it | No | Pull request / code review |
| Rebuild a server | Repeat the commands from memory | ansible-playbook site.yml |
| Simulate before applying | Command by command | The whole playbook with --check --diff |
- What a playbook is
A playbook is a YAML file containing a list of plays. Each play says which hosts to work on and which tasks to run on them, in order. Each task invokes a module with its parameters, exactly as you did with -m and -a in an ad hoc command.
The word comes from sports: a playbook is a team's book of plays. Each play assigns a role to a group of players (hosts) and describes what each one has to do.
Important properties:
- It's declarative: you describe the final state ("
htoppresent", "time zoneEurope/Madrid"), not the commands needed to get there. - It's idempotent if you use idempotent modules: running it twice changes nothing the second time.
- It runs in order: tasks are applied from top to bottom, and each one finishes on every host before moving on to the next (the
linearstrategy, Lesson 1.4). - It uses everything you already have: the inventory, the variables in
group_vars/andhost_vars/and the settings inansible.cfgapply just as they do with theansiblecommand.
- The hierarchy: playbook, plays, tasks and modules
flowchart TD
PB["Playbook<br/>(file site.yml, common.yml...)"] --> P1["Play 1<br/>hosts: webservers"]
PB --> P2["Play 2<br/>hosts: dbservers"]
P1 --> T1["Task: Install nginx"]
P1 --> T2["Task: Start nginx"]
P2 --> T3["Task: Install PostgreSQL"]
T1 --> M1["Module<br/>ansible.builtin.apt"]
T2 --> M2["Module<br/>ansible.builtin.systemd_service"]
T3 --> M3["Module<br/>ansible.builtin.apt"]
| Level | What it is | Ad hoc equivalent |
|---|---|---|
| Playbook | A .yml file with one or more plays |
A script with several ansible commands |
| Play | Associates a group of hosts with a list of tasks and options (become, variables…) |
The host pattern (aurora, webservers) and options such as -b |
| Task | A call to a module with a name and parameters | An ansible ... -m ... -a ... command |
| Module | The program that does the work on the host | -m ansible.builtin.apt |
A playbook with a single play is the most common case when you're starting out; in Lesson 3.4 you will see files with several plays and how to chain playbooks together.
- A first look: Aurora's
common.yml playbook
common.yml playbookLet's turn the two ad hoc commands from section 1 into a playbook. Create the common.yml file at the root of the repository:
---
- name: Common configuration for Aurora Store servers
hosts: aurora
become: true
tasks:
- name: Install htop
ansible.builtin.apt:
name: htop
state: present
update_cache: true
cache_valid_time: 3600
- name: Set the time zone
community.general.timezone:
name: "{{ aurora_timezone }}"Line by line:
---marks the start of a YAML document. It's optional, but it's the convention in every Ansible file.- name: Common configuration...starts a play (the dash-marks an item in a list: the playbook is a list of plays). The name appears in the output; always write one.hosts: aurorastates which hosts the play acts on: theauroraparent group you created in Lesson 2.1 (web1, web2 and db1). It accepts the same patterns as theansiblecommand.become: trueis the equivalent of-b: every task in the play runs withsudo. Since you leftbecome = Falseinansible.cfg, here you enable it only where it's needed.tasks:opens the play's list of tasks.- Each task starts with
- name:(a readable description), followed by the module with its FQCN and its parameters indented below it, one per line, instead of the-a 'name=htop state=present'string. "{{ aurora_timezone }}"is the variable you defined ininventory/group_vars/all/aurora.yml. It's wrapped in quotes because of a YAML rule you will see in the next lesson.
Compare the two forms:
| Ad hoc command | Playbook |
|---|---|
ansible aurora |
hosts: aurora |
-b |
become: true |
-m ansible.builtin.apt |
ansible.builtin.apt: |
-a 'name=htop state=present update_cache=true cache_valid_time=3600' |
Parameters on indented YAML lines |
| No description | name: Install htop |
Watch the indentation: YAML uses spaces to know what belongs to what. Always use 2 spaces per level and never tabs. Lesson 3.2 is entirely devoted to this.
- Running a playbook with
ansible-playbook
ansible-playbookPlaybooks are run with the ansible-playbook command, not with ansible:
You don't need -i: ansible.cfg points to the inventory (Lesson 2.3). Nor do you need a user or a key. The most common options, many of which you already know:
| Option | What it's for |
|---|---|
-l web1 / --limit web1 |
Restrict the run to some of the play's hosts |
--syntax-check |
Check the syntax without running anything |
--check |
Simulate without changing anything |
--diff |
Show the differences in files |
--list-hosts, --list-tasks |
See which hosts and which tasks would run |
-e 'variable=value' |
Pass extra variables (Lesson 3.5) |
-v, -vv, -vvv |
More detail in the output (Lesson 3.7) |
-K |
Prompt for the sudo password (not needed in the lab) |
Before launching a new playbook, checking its syntax is a very healthy habit:
If all you see is the file name, the syntax is correct. Now run it for real:
- Reading the output and the
PLAY RECAP
PLAY RECAPOn freshly restored machines, the output will look something like this (the order of the hosts within each task may vary, because they run in parallel):
PLAY [Common configuration for Aurora Store servers] ***************************
TASK [Gathering Facts] *********************************************************
ok: [web2]
ok: [db1]
ok: [web1]
TASK [Install htop] ************************************************************
changed: [web1]
changed: [db1]
changed: [web2]
TASK [Set the time zone] *******************************************************
changed: [web2]
changed: [web1]
changed: [db1]
PLAY RECAP *********************************************************************
db1 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
web1 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
web2 : ok=3 changed=2 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0What each part means:
PLAY [...]: a play begins; it shows itsname.TASK [Gathering Facts]: a task you didn't write. Before yours, Ansible runs thesetupmodule to collect information about each host (the facts: operating system, IPs, memory…). You will study it in Lesson 3.5.TASK [Install htop]: each task shows itsnameand the result per host, with the same colors as in ad hoc commands: green (ok), yellow (changed), red (failed/fatal), cyan (skipping).PLAY RECAP: the final summary, one line per host.
| Counter | Meaning |
|---|---|
ok |
Tasks that finished successfully (includes the changed ones) |
changed |
Tasks that modified something on the host |
unreachable |
The host didn't respond over SSH |
failed |
Tasks that failed (the host stops running the rest of the play) |
skipped |
Tasks skipped because of a condition (Lesson 3.6) |
rescued |
Errors recovered with a rescue block (Lesson 5.5) |
ignored |
Errors ignored with ignore_errors (Lesson 5.5) |
Notice that ok=3 includes the two changed tasks and the fact gathering. Run the playbook again:
PLAY RECAP *********************************************************************
db1 : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
web1 : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
web2 : ok=3 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0changed=0: the state was already the desired one, and Ansible didn't touch anything. This is idempotency in action, and it's the simplest proof that a playbook is well written: the second run must not change anything.
In addition, ansible-playbook finishes with an exit code you can use in scripts and in CI/CD (Module 8):
| Code | Meaning |
|---|---|
0 |
Everything OK |
2 |
Some host had failed tasks |
4 |
Some host was unreachable |
1, 5, 250 or others |
General error, invalid options or unexpected error |
A syntax error in the playbook also returns
4. That's why, in a script, the safe approach is to treat any code other than0as a problem.
- Playbooks, ad hoc commands and scripts
Playbooks don't entirely replace ad hoc commands: each tool has its place.
| Aspect | Ad hoc command | Playbook | Shell script |
|---|---|---|---|
| Typical use | One-off queries and actions | Configuration and deployments that are repeated | Local or very specific automation |
| Stored in Git | No | Yes | Yes |
| Idempotency | Depends on the module | Depends on the modules (usually yes) | Must be programmed by hand |
| Several ordered steps | No (one module per command) | Yes | Yes |
| Several hosts in parallel | Yes | Yes | No (must be programmed) |
| Logic (conditions, loops) | No | Yes (when, loop) |
Yes |
Simulation (--check --diff) |
Yes | Yes, of the whole set | No |
| Readability for the team | Low | High (YAML with names) | Varies |
A rule of thumb for Aurora:
- Ad hoc to ask questions ("which nginx version is installed?", "how much disk is left?") or for a single emergency action.
- Playbook for anything that must stay configured or that you are going to repeat.
- Scripts only when no module exists and the logic is complex; and even then, it's better to launch them from a playbook (
ansible.builtin.script) so they are recorded.
- Where playbooks live in
aurora-infra
aurora-infraIn this course, playbooks are stored at the root of the repository, next to ansible.cfg. This is the layout recommended by the Ansible documentation, and it has a practical advantage: when you create the roles/ directory in Module 4, the playbooks will find it automatically because it will sit right next to them.
aurora-infra/
├── ansible.cfg
├── common.yml ← new: common configuration for all servers
├── inventory/
│ ├── hosts.yml
│ ├── group_vars/
│ └── host_vars/
└── lab/
└── VagrantfileThroughout the module you will add webservers.yml (Lesson 3.3), dbservers.yml and site.yml (Lesson 3.4). Commit the first one now:
Common Mistakes and Tips
- Using
ansibleinstead ofansible-playbook:ansible common.ymlinterpretscommon.ymlas a host pattern and replies that it can't find any hosts. Playbooks always go withansible-playbook. - Forgetting
become: true: theapttask fails with a permissions error (Could not open lock file...). If a task needsroot, the play (or the task) must havebecome. - Mixing tabs and spaces: the YAML error usually points to a different line from the one causing the problem. Set up your editor to insert spaces when you press Tab.
- Tasks without a
name: they work, but the output shows only the module name and nobody understands what each step does. Always give them a name that starts with a verb. - Running from another directory: if you launch
ansible-playbookoutside~/aurora-infra, itsansible.cfgisn't read and the inventory isn't found. Always work from the root of the repository. - Tip: run every new playbook twice. If anything shows up as
changedthe second time, there's a task that isn't idempotent and it's worth reviewing.
Exercises
Exercise 1: From ad hoc to playbook
In Lesson 2.4 you created the /etc/motd file with this command:
ansible aurora -m ansible.builtin.copy \
-a 'content="Aurora Store server. Restricted access.\n" dest=/etc/motd mode=0644' -bWrite a motd.yml playbook (a throwaway one; you won't keep it in the repository) that does the same thing. Run it twice and note down the PLAY RECAP counters.
Exercise 2: Reading the PLAY RECAP
With the machines running, shut down web2 (cd lab && vagrant halt web2 && cd ..) and run ansible-playbook common.yml. Which counters change for web2? Which exit code does the command return? Start web2 again when you're done.
Exercise 3: Choosing the tool
For each situation, say whether you would use an ad hoc command, a playbook or a script: (a) check the free disk space on every server right now; (b) make sure every server has htop and the correct time zone; (c) reboot web2 once because it has hung.
Solutions
Exercise 1.
---
- name: Aurora Store welcome message
hosts: aurora
become: true
tasks:
- name: Create /etc/motd
ansible.builtin.copy:
content: "Aurora Store server. Restricted access.\n"
dest: /etc/motd
mode: "0644"ansible-playbook motd.yml # db1, web1, web2: ok=2 changed=1
ansible-playbook motd.yml # db1, web1, web2: ok=2 changed=0
rm motd.ymlok=2 because it counts the fact gathering and the task. Notice that the mode is written as "0644" in quotes: the next lesson explains why. The final motd will be added to common.yml in Lesson 3.2.
Exercise 2. web2 appears in one task as fatal: [web2]: UNREACHABLE! and disappears from the following ones. In the PLAY RECAP it shows ok=0 changed=0 unreachable=1 failed=0. The other hosts finish normally. echo $? returns 4 (unreachable host). Start it with cd lab && vagrant up web2 && cd ...
Exercise 3. (a) Ad hoc command: ansible aurora -a 'df -h /'; it's a one-off query. (b) Playbook: it's configuration that must always be maintained; in fact, it's common.yml. (c) Ad hoc command (ansible web2 -m ansible.builtin.reboot -b): it's a single emergency action that doesn't describe a desired state.
Conclusion
You have made the leap from loose commands to code: a playbook is a YAML file with a list of plays; each play associates a group of hosts with an ordered list of tasks, and each task calls a module. You have turned the htop and time zone commands into common.yml, run it with ansible-playbook, learned to read the PLAY RECAP counters and the exit code, and verified idempotency with a second run that changed nothing. You have also set a convention: Aurora's playbooks live at the root of aurora-infra and are stored in Git. To write playbooks without errors, you need to master the language they're written in. In the next lesson, Essential YAML for Ansible, you will learn the YAML syntax Ansible uses: maps, lists, indentation, quotes, booleans and blocks of text, and how to interpret a syntax error.
Ansible Course: From Beginner to Advanced
Module 1: Introduction to Ansible
- What Is Ansible?
- Installing Ansible
- Setting Up the Practice Lab
- Ansible Architecture
- Basic Ansible Commands
Module 2: Ansible Fundamentals
- Inventory Files
- Inventory Variables: group_vars and host_vars
- Configuring Ansible (ansible.cfg)
- Ad Hoc Commands
- Ansible Modules
- Collections and Fully Qualified Names (FQCN)
Module 3: Playbooks
- Introduction to Playbooks
- Essential YAML for Ansible
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
- Registering Results and Debugging Playbooks
Module 4: Roles
- Introduction to Roles
- Creating Roles
- Role Directory Structure
- Using Roles in Playbooks
- Reusing Tasks: include and import
- Role Dependencies and Argument Validation
Module 5: Advanced Playbook Techniques
- Handlers
- Jinja2 Templates
- Filters and Lookups
- Ansible Vault
- Error Handling
- Tags and Selective Execution
- Rolling Deployments and Delegation
- Optimizing Playbooks
Module 6: Ansible Galaxy
- What Is Ansible Galaxy?
- Using Ansible Galaxy
- Managing Dependencies with requirements.yml
- Creating and Sharing Roles
- Creating Your Own Collections
Module 7: Ansible Tower, AWX and Automation Platform
- Introduction to Ansible Tower and AWX
- Installing AWX
- Using AWX: Job Templates and Jobs
- Managing Projects and Inventories
- Credentials, Permissions (RBAC) and Workflows
- Execution Environments and ansible-navigator
Module 8: Ansible for DevOps
- Ansible and Docker
- Ansible and Kubernetes
- CI/CD with Ansible
- Ansible in Cloud Environments
- Ansible and Terraform
Module 9: Ansible Best Practices
- Code Organization
- Security Best Practices
- Performance Tuning
- Code Quality: ansible-lint and yamllint
- Testing Ansible Code with Molecule
Module 10: Advanced Ansible Topics
- Custom Modules
- Dynamic Inventory
- Ansible Plugins
- The Ansible API and ansible-runner
- Event-Driven Ansible
