Chapter Four

Playbooks — The Core

The YAML rules that bite, the play as the unit that binds hosts to tasks, and the flags you run a playbook with daily. Handlers that bounce a service only when its config moved, privilege escalation with become, and the fixed lifecycle every run follows — built around the real Larkspur web and database stack.

7 topics

A playbook is where Ansible stops being a one-off command and becomes a checked-in description of a whole system. This chapter writes a real one: site.yml, which installs and configures nginx and gunicorn on the Larkspur web tier and PostgreSQL 16 on db1.larkspur.io, with handlers that reload services only when a config file actually changes. Everything you reach for daily lives in these seven pages.

The order is deliberate. YAML first, because every playbook is YAML and its quirks masquerade as Ansible bugs. Then the play — the unit that binds hosts to tasks — how you run it, how tasks invoke modules, the two identity topics that have no analog in a provisioning tool (handlers and become), and finally the fixed lifecycle every run follows from fact gathering to handlers at the end.

Topics in This Chapter

Topic 19
YAML for Ansible
Indentation as syntax, lists versus dictionaries, the truthiness trap, and quoting discipline. The handful of YAML rules that bite Ansible users, and why a parse error is almost always a YAML problem in an Ansible costume.
ConceptSyntax
Topic 20
Playbook Anatomy
A play binds a set of hosts to a set of tasks. Where hosts, become, and vars live, how play-level scope works, and why a playbook is an ordered list of plays that encodes a multi-tier rollout.
ConceptPlaybooks
Topic 21
Running Playbooks
The base command and the flags you reach for daily: --limit to scope hosts, --tags to scope tasks, -v for verbosity, --check to preview. The exit code is the verdict CI watches.
Workflow
Topic 22
Tasks and Module Invocation
The three parts of a task, FQCN versus short module names, and the name discipline that makes run output legible. What an unnamed task costs you, and the changed-versus-ok distinction.
PlaybooksModules
Topic 23
Handlers and notify
A task that runs only when something changed and notified it, once, at the end of the play. notify and listen, the doesn't-fire traps, and meta: flush_handlers — pure Ansible identity with no provisioning analog.
ConceptPlaybooks
Topic 24
Privilege Escalation with become
Connect as deploy, act as root. become, become_user, and become_method, per-play versus per-task escalation, --ask-become-pass, and why SSHing directly as root is the posture Ansible is built to avoid.
ConceptSecurity
Topic 25
Play Execution Lifecycle
Gather facts, run tasks top to bottom, then notified handlers at the end — repeated per host. The linear strategy, why re-convergence needs no state file, and how a run stays idempotent against the live machine.
ConceptWorkflow