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

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.

← Format your YAML now