An Ansible playbook is a YAML file that declares one or more plays, each mapping a group of managed hosts to an ordered list of tasks that Ansible executes to reach a desired configuration. In infrastructure as code, the playbook is the primary unit of automation in Ansible: it turns server setup, application deployment and multi-step operational procedures into version-controlled, reviewable and repeatable text.
Playbooks are agentless by design. Ansible connects to targets over SSH for Linux and UNIX systems or WinRM for Windows, copies small modules, runs them and removes them, so no permanent daemon is needed on the managed nodes.
How an Ansible playbook is structured
A playbook is a list of plays, and each play is a list of tasks. A play names its target with the hosts keyword, which refers to groups or patterns defined in the inventory, and sets execution options such as privilege escalation with become.
Each task calls exactly one module with its arguments, for example ansible.builtin.apt to install a package or ansible.builtin.template to render a Jinja2 file. Tasks run top to bottom on all targeted hosts in parallel, task by task, under the default linear strategy.
| Element | Purpose | Typical keyword |
|---|---|---|
| Play | Binds a host pattern to tasks | hosts |
| Task | Runs one module with arguments | name plus module name |
| Handler | Runs only when notified by a change | handlers, notify |
| Variables | Parameterize hosts and environments | vars, vars_files |
| Role | Reusable bundle of tasks, files and defaults | roles, include_role |
| Block | Groups tasks for shared error handling | block, rescue, always |
Handlers solve a common problem elegantly: a web server should restart only when its configuration actually changed. A task that modifies the file notifies the handler, and Ansible runs the handler once at the end of the play, regardless of how many tasks notified it.
Idempotence and the desired state model
Well-written playbooks are idempotent: running them repeatedly produces the same result and reports no changes once the system already matches the description. Most modules achieve this by checking current state before acting, so state: present installs a package only when it is missing.
Each task reports one of several result statuses, which Ansible summarizes in the play recap at the end of a run. The table explains how operators interpret them.
| Status | Meaning | Operator response |
|---|---|---|
| ok | Host already in desired state | None needed |
| changed | Module modified the host | Expected on first run or after drift |
| failed | Module returned an error | Investigate; host stops processing |
| skipped | Condition in when was false | Verify the condition is intended |
| unreachable | Connection to host failed | Check network, SSH keys or WinRM |
Idempotence is not automatic. The command and shell modules always report a change unless the author adds creates, removes or a changed_when expression, which is a frequent source of noisy, misleading runs.
Ansible playbook compared with other infrastructure as code tools
An Ansible playbook is procedural in execution but declarative at the task level. Tasks describe the desired state of each resource, yet the order in which they appear is the order in which they run, which distinguishes playbooks from fully declarative tools.
| Tool | Primary focus | State tracking | Agent required |
|---|---|---|---|
| Ansible playbook | Configuration and orchestration | No state file; checks live state | No |
| Terraform | Provisioning cloud resources | Terraform state file | No |
| Puppet | Continuous configuration enforcement | Catalog compiled per node | Usually yes |
| Chef | Configuration through Ruby recipes | Node object on server | Usually yes |
| Salt | Configuration and remote execution | State files on master | Usually yes |
Many teams combine tools: Terraform provisions the virtual machines, while playbooks configure the operating system and deploy applications on them. Because Ansible keeps no state file, it cannot by itself detect resources that were removed from the code, which makes it less suited to full lifecycle management of cloud resources.
Writing and running playbooks in practice
Playbooks are run with the ansible-playbook command against an inventory of hosts and groups. Static inventories are INI or YAML files, while dynamic inventory plugins query cloud APIs so that newly launched instances are targeted automatically.
- Check mode (
--check) simulates a run and reports what would change without modifying hosts. - Diff mode (
--diff) shows line-level changes to templated and copied files. - Tags limit a run to selected tasks, for example only the deployment steps.
- Limit (
--limit) restricts the run to a subset of hosts, which supports canary rollouts. - Ansible Vault encrypts secrets such as passwords inside variable files.
The serial keyword enables rolling updates in batches, such as 10 percent of web servers at a time, while max_fail_percentage aborts the rollout if too many hosts fail. Together they make playbooks safe for production deployments behind load balancers.
Common mistakes and limitations
Most playbook problems come from treating Ansible like a shell script. The table lists frequent symptoms, their causes and the usual fix.
| Symptom | Likely cause | Fix |
|---|---|---|
| Every run reports changes | Unguarded shell or command tasks | Use a proper module or changed_when |
| Slow runs on large fleets | Fact gathering and low forks | Cache facts, raise forks, use pipelining |
| Secrets visible in logs | Missing no_log on sensitive tasks | Set no_log and store values in Vault |
| Unexpected variable values | Variable precedence conflicts | Simplify layers; prefer role defaults |
| Playbook breaks after upgrade | Unpinned collections | Pin versions in requirements.yml |
Playbooks also run only when someone or something triggers them. Unlike agent-based tools, Ansible does not continuously correct configuration drift, so teams schedule runs from a CI pipeline or an automation controller to keep hosts aligned.
In everyday language
An Ansible playbook is like a detailed checklist for setting up computers. Instead of a technician logging in to each server and following written steps by hand, the checklist is stored in a file that Ansible reads and carries out on hundreds of machines at once.
Each item on the list says how things should end up, such as which program must be installed. If a machine already matches, Ansible leaves it alone. The key benefit is consistency: every server is set up the same way, every time.
Seen in the real world
A university IT department manages about 80 Linux web servers that host departmental websites. Security patches and configuration changes used to take two administrators most of a week, and servers slowly drifted apart in versions and settings.
The team writes a playbook with roles for the base operating system, the Nginx web server and the monitoring agent. A dynamic inventory reads the server list from the virtualization platform, and the patch play uses serial: 20% so that only a fifth of the servers leave the load balancer at once. Database passwords are stored with Ansible Vault.
Running the playbook from the CI pipeline every night now reapplies the approved configuration to all 80 servers in about 25 minutes. A full patch cycle that once took days finishes in an afternoon, and the nightly recap immediately shows any server whose state changed unexpectedly.