TExcelTAD
Home › Configuration Management: Ansible › Your First Playbook

Your First Playbook

A playbook is a YAML file with a list of plays. Each play maps a group of hosts to an ordered list of tasks, and each task calls one module.

yaml
---
- name: Configure web servers          # play 1
  hosts: web                           # which hosts (a pattern)
  gather_facts: false                  # skip fact gathering (faster, when facts aren't needed)
  vars:
    app_dir: /home/learner/app
  tasks:
    - name: Create the app directory   # task 1
      ansible.builtin.file:            # the module, by its fully qualified name
        path: "{{ app_dir }}"          # module arguments
        state: directory
        mode: "0755"

- name: Configure database servers     # play 2
  hosts: db
  tasks: []

The rules that trip people up:

  • Name every play and task. The name is what the output and the logs show; ansible-lint insists on it.
  • Quote values that start with {{. YAML would read path: {{ app_dir }} as a dictionary and fail.
  • Quote file modes ("0644"). An unquoted 0644 is the octal number 420 in YAML 1.1, and 644 would be decimal 644, which is a different mode.
  • Use the fully qualified collection name (FQCN) ansible.builtin.file, not just file; see Collections & FQCNs.

Running it

bash · try it yourself
mkdir site && cd site
cat > ansible.cfg <<'INI'
[defaults]
inventory = hosts.ini
interpreter_python = auto_silent
forks = 1
INI
cat > hosts.ini <<'INI'
[web]
web1 ansible_connection=local app_dir=/home/learner/web1
web2 ansible_connection=local app_dir=/home/learner/web2
INI
cat > site.yml <<'YML'
---
- name: Configure web servers
  hosts: web
  gather_facts: false
  tasks:
    - name: Create the app directory
      ansible.builtin.file:
        path: "{{ app_dir }}"
        state: directory
        mode: "0755"

    - name: Write the app config
      ansible.builtin.copy:
        dest: "{{ app_dir }}/app.conf"
        content: |
          listen = 8080
          name = {{ inventory_hostname }}
        mode: "0644"
YML
ansible-playbook site.yml
cat ../web2/app.conf

PLAY [Configure web servers] ***************************************************

TASK [Create the app directory] ************************************************
changed: [web1]
changed: [web2]

TASK [Write the app config] ****************************************************
changed: [web1]
changed: [web2]

PLAY RECAP *********************************************************************
web1                       : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
web2                       : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

listen = 8080
name = web2

Reading the output

  • PLAY [...] and TASK [...] headers show progress. Within a task, each host reports one status:
Status Meaning
ok the host already matched; nothing done
changed the module changed something
skipping a when: condition was false
failed the task failed; this host stops (other hosts go on)
unreachable Ansible could not connect
  • PLAY RECAP sums up per host. In CI, check the exit code: 0 all good, 2 a task failed, 4 a host was unreachable.

Execution order

By default (the linear strategy) Ansible runs task 1 on every host, waits for all of them, then task 2 on every host, and so on. A host that fails drops out of the rest of the play. The remote hosts lesson shows serial and the free strategy, which change this.

Idempotency: the second run

Run it again and nothing changes:

bash · try it yourself
mkdir site && cd site
cat > site.yml <<'YML'
---
- name: Idempotency demo
  hosts: localhost
  gather_facts: false
  tasks:
    - name: Create the app directory
      ansible.builtin.file:
        path: /home/learner/app
        state: directory
        mode: "0755"
    - name: Write the app config
      ansible.builtin.copy:
        dest: /home/learner/app/app.conf
        content: "listen = 8080\n"
        mode: "0644"
YML
for run in 1 2; do ansible-playbook site.yml | grep '^localhost'; done
echo "listen = 9999" > /home/learner/app/app.conf      # someone edits it by hand
ansible-playbook site.yml | grep -E '^(changed|ok):|^localhost'
cat /home/learner/app/app.conf
localhost                  : ok=2    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
ok: [localhost]
changed: [localhost]
localhost                  : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
listen = 8080

The third run found the hand edit (drift), put the file back and reported exactly one change. That is how configuration management keeps a fleet consistent: run the playbooks regularly (from CI or a scheduler such as AWX) and changed counts tell you where somebody worked around the code.

Checking before running

bash · try it yourself
cat > site.yml <<'YML'
---
- name: Syntax demo
  hosts: localhost
  gather_facts: false
  tasks:
    - name: First task
      ansible.builtin.debug:
        msg: one
    - name: Second task
      ansible.builtin.debug:
        msg: two
      tags: [config]
YML
ansible-playbook site.yml --syntax-check
ansible-playbook site.yml --list-tasks

playbook: site.yml

playbook: site.yml

  play #1 (localhost): Syntax demo	TAGS: []
    tasks:
      First task	TAGS: []
      Second task	TAGS: [config]

--syntax-check parses the playbook without running it, --list-tasks and --list-hosts show what would run. Both are cheap CI steps; ansible-lint goes further.

Test yourself

Why must path: {{ app_dir }} be written as path: "{{ app_dir }}"?

  1. Jinja2 requires quotes
  2. Unquoted, YAML reads the leading { as the start of a dictionary
  3. Paths must always be quoted
  4. Ansible strips braces otherwise

In the default linear strategy, how are tasks run on three hosts?

  1. All tasks on host 1, then all on host 2
  2. Task 1 on all hosts, then task 2 on all hosts
  3. Random order
  4. Only on the first host

A playbook run reports changed=1 on a server where nobody changed the playbook. What does it most likely mean?

  1. Ansible is broken
  2. Someone changed the server by hand (drift), and Ansible put it back
  3. The inventory is wrong
  4. The task is skipped