Foundations / Lesson 3 of 3

Playbooks and Tasks

Write your first playbook and see how plays, tasks and modules fit together.

8 min Beginner 8 steps
web-1Install nginxsite.ymlPlay: webserversCopy confignginx runningStart nginx

IN THIS LESSON

Step 1 of 8

STEP 1 / 8

A playbook is a YAML file

A playbook is written in YAML, so it is easy to read and easy to keep in Git. At the top level it is a list of plays.

---
- name: Configure web servers
  hosts: webservers
  become: true
  tasks:
    - name: Install nginx
      ansible.builtin.apt:
        name: nginx
        state: present

← → step · R replay · Space play/pause

YOU'LL LEARN

  • How a playbook is structured into plays and tasks
  • How tasks call modules
  • What idempotency means and why it matters
  • How to preview a run with check mode
  1. A playbook is a YAML file. A playbook is written in YAML, so it is easy to read and easy to keep in Git. At the top level it is a list of plays.
  2. A play maps hosts to tasks. A play picks which hosts to target and which tasks to run on them. Setting become: true runs the tasks with elevated privileges, like sudo.
  3. Tasks run in order. A task is one step. Ansible runs them from top to bottom on each host and stops that host if a task fails. Giving each task a name makes the output readable.
  4. Every task calls a module. The module is what does the work: apt installs packages, copy puts files in place, service manages services. You state the outcome you want, and the module works out how to reach it.
  5. Tasks are applied to the hosts. For each host in the play, Ansible connects, runs the tasks in order and reports the result of each one.
  6. Idempotent by design. Run the playbook again and nothing needs to change, because nginx is already installed, the file already matches and the service is already running. Tasks report ok instead of changed. Be careful with the command and shell modules, which are not idempotent unless you add conditions.
  7. Preview with check mode. Add --check to see what would change without changing anything, and --diff to see the exact file differences. Not every module supports check mode, but most common ones do.
  8. Recap. A playbook is a readable list of desired outcomes that Ansible applies safely and repeatedly.