YAML for Ansible Playbooks: A Beginner's Guide
Ansible playbooks are YAML files that describe a sequence of actions to run on one or more servers — install a package, copy a file, restart a service. If you can read the structure once, you can read almost any playbook you'll come across.
---
- name: Configure web servers
hosts: webservers
become: true
tasks:
- name: Install nginx
apt:
name: nginx
state: present
- name: Start nginx
service:
name: nginx
state: started
Reading the structure
The whole file is a list — notice the dash right before name: Configure web servers — because a playbook can contain multiple "plays," each targeting different servers. This one has just one play, which runs on the group of machines called webservers and uses become: true to run with elevated privileges.
tasks is itself a list of steps, run top to bottom. Each task names an Ansible "module" — here, apt and service — with its own set of nested options underneath. Once you recognize this pattern (a task name, a module name, and indented options), most playbooks stop looking like a wall of text and start looking like a fairly readable checklist.
The mistakes specific to Ansible YAML
- Forgetting the leading dash on a play or task. Since plays and tasks are list items, a missing dash turns what should be a new item into an invalid key on the previous one.
- Module options indented at the wrong level.
nameandstateunderaptneed to be indented consistently as children ofapt, not as siblings of the task's ownname. - Boolean-like strings for package names. A package literally named something like
yesornowould need quoting — rare, but worth remembering given YAML's boolean-guessing behavior covered in our data types article.
Before running ansible-playbook against real servers, it's worth pasting a hand-edited playbook into our validator first — catching a structural typo before it runs against production machines is a lot less stressful than after.