You know what a playbook is and you know the YAML syntax you need. Now it's time to write a real one, from start to finish: the playbook that turns web1 and web2 into Aurora Store's web servers. You will build it step by step, the way it's done in a real project: install nginx, prepare the website directory, publish a first store page, configure the site, make sure the service starts with the system and open the firewall. Along the way you will learn the professional workflow with ansible-playbook: check the syntax, list hosts and tasks, simulate with --check and --diff, run, prove idempotency with a second run, verify the result with curl and save the work in Git.

Contents

  1. What we are going to build
  2. Step 1: the play skeleton and installing nginx
  3. Step 2: the website directory and the home page
  4. Step 3: the Aurora site in nginx
  5. Step 4: the nginx service
  6. Step 5: the firewall with community.general.ufw
  7. The complete playbook
  8. Before running: --syntax-check, --list-hosts and --list-tasks
  9. Running and checking idempotency
  10. Verifying the result with curl
  11. Simulating changes with --check and --diff
  12. Saving the work in Git

  1. What we are going to build

We start from clean machines (except for what common.yml already applies). When we're done, every web server must meet this desired state:

# Desired state Module
1 The nginx package is installed ansible.builtin.apt
2 The {{ aurora_web_root }} directory (/var/www/aurora) exists ansible.builtin.file
3 There is a store index.html page ansible.builtin.copy
4 nginx serves that folder on port {{ nginx_port }} and the default site is disabled ansible.builtin.copy and ansible.builtin.file
5 nginx is started and enabled at boot ansible.builtin.systemd_service
6 The firewall allows SSH and HTTP and is active community.general.ufw

Notice that we write states, not orders: "nginx installed", not "install nginx". That's how we'll think about each task.

The aurora_web_root, nginx_port and aurora_domain variables already exist in the inventory (Lesson 2.2), so the playbook doesn't need to define any. Check it:

cd ~/aurora-infra
ansible-inventory --host web1

  1. Step 1: the play skeleton and installing nginx

Create webservers.yml at the root of the repository with the play and the first task:

---
- name: Configure the Aurora Store web servers
  hosts: webservers
  become: true

  tasks:
    - name: Install nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true
        cache_valid_time: 3600
  • hosts: webservers: only web1 and web2.
  • become: true: installing packages and writing to /etc requires root.
  • update_cache: true with cache_valid_time: 3600: updates the package list (apt update) only if it's more than an hour old. Without cache_valid_time, it would always update and the task wouldn't be as fast on subsequent runs.

You can already run it to see the work progress:

ansible-playbook webservers.yml

On Ubuntu, the nginx package starts the service automatically after it's installed, with its default welcome page. We are going to replace it with Aurora's.

  1. Step 2: the website directory and the home page

Add two tasks after the previous one (inside tasks:, with the same indentation):

    - name: Create the web root directory
      ansible.builtin.file:
        path: "{{ aurora_web_root }}"
        state: directory
        owner: root
        group: root
        mode: "0755"

    - name: Publish the store home page
      ansible.builtin.copy:
        dest: "{{ aurora_web_root }}/index.html"
        owner: root
        group: root
        mode: "0644"
        content: |
          <!DOCTYPE html>
          <html lang="en">
          <head>
            <meta charset="utf-8">
            <title>Aurora Store - Specialty Coffee</title>
          </head>
          <body>
            <h1>Aurora Store</h1>
            <p>Specialty coffee, roasted every week in small batches.</p>
            <p><small>Served by {{ inventory_hostname }} - {{ aurora_domain }}</small></p>
          </body>
          </html>
  • file with state: directory creates the directory if it doesn't exist (and with the given permissions); if it already exists with those permissions, it does nothing.
  • copy with content: writes the file from a piece of text instead of copying a local file. The | literal block (Lesson 3.2) preserves the lines of the HTML. The {{ }} variables are substituted for each host, so each server will display its own name: very handy later on for checking which server is responding behind the load balancer.
  • For now the owner is root. Once the deploy user exists in code (Lesson 3.6), the directory will become its property.

For more complex pages or configurations, copy with content: falls short. In Lesson 5.2 you will learn to use Jinja2 templates with the template module. For now, content: is perfect.

  1. Step 3: the Aurora site in nginx

On Ubuntu, nginx organizes sites like this: each site's configuration lives in /etc/nginx/sites-available/, and it's enabled by creating a symbolic link in /etc/nginx/sites-enabled/. The package comes with a default site enabled that serves /var/www/html. We need three tasks:

    - name: Configure the Aurora site in nginx
      ansible.builtin.copy:
        dest: /etc/nginx/sites-available/aurora
        owner: root
        group: root
        mode: "0644"
        content: |
          # Managed by Ansible (aurora-infra). Do not edit by hand.
          server {
              listen {{ nginx_port }} default_server;
              listen [::]:{{ nginx_port }} default_server;
              server_name {{ aurora_domain }} www.{{ aurora_domain }};

              root {{ aurora_web_root }};
              index index.html;

              location / {
                  try_files $uri $uri/ =404;
              }
          }
      register: nginx_site_config

    - name: Enable the Aurora site
      ansible.builtin.file:
        src: /etc/nginx/sites-available/aurora
        dest: /etc/nginx/sites-enabled/aurora
        state: link
      register: nginx_site_enabled

    - name: Disable the default nginx site
      ansible.builtin.file:
        path: /etc/nginx/sites-enabled/default
        state: absent
      register: nginx_default_site
  • The first line of the file warns that it's managed by Ansible: if someone edits it by hand, the next run will overwrite their changes. It's a highly recommended convention.
  • file with state: link creates the symbolic link dest pointing to src.
  • file with state: absent removes the link to the default site (the original file stays in sites-available/, in case you ever need it).
  • listen ... default_server makes our site answer any request, including those addressed to the IP. That's why the default site has to be disabled: two default_server sites on the same port are a configuration error.

What is register:? It stores the task's result in a variable (nginx_site_config, etc.). We need it for the next step: nginx only reads its configuration when it starts or reloads, so after changing it you have to reload it, but only if something has changed. register is covered in depth in Lesson 3.7; for now it's enough to know that the registered variable has a changed attribute that is true if the task changed something.

  1. Step 4: the nginx service

    - name: Ensure nginx is started and enabled
      ansible.builtin.systemd_service:
        name: nginx
        state: started
        enabled: true

    - name: Reload nginx if its configuration has changed (temporary)
      ansible.builtin.systemd_service:
        name: nginx
        state: reloaded
      when: nginx_site_config.changed or nginx_site_enabled.changed or nginx_default_site.changed
  • The first task declares a state: nginx running now (started) and when the server boots (enabled: true). If it already is, it does nothing.
  • The second one is not a state but an action: state: reloaded reloads nginx every time it runs. That's why we add when:, a condition (Lesson 3.6) that only lets the task run if any of the three configuration tasks has changed something. If the condition isn't met, the task shows up as skipping.

Why "temporary"? Because this pattern (register + when: ... .changed) works but is awkward: every new configuration task forces you to extend the condition. Ansible has a mechanism designed precisely for this, handlers, which you will study in Lesson 5.1. Until then, we'll use this pattern in Aurora whenever a configuration change requires reloading or restarting a service.

  1. Step 5: the firewall with community.general.ufw

Ubuntu includes the ufw firewall, disabled by default. We enable it on the web servers, letting through only SSH and HTTP. Order matters: first the SSH rules, then enable. If you enable ufw without allowing SSH, you will lose access to the server (and so will Ansible).

    - name: Allow SSH through the firewall
      community.general.ufw:
        rule: allow
        name: OpenSSH

    - name: Allow HTTP through the firewall
      community.general.ufw:
        rule: allow
        port: "{{ nginx_port }}"
        proto: tcp

    - name: Enable the firewall
      community.general.ufw:
        state: enabled
  • name: OpenSSH uses the application profile installed by the SSH server package (port 22/tcp).
  • port: "{{ nginx_port }}" opens the port from the inventory variable (80).
  • state: enabled enables ufw with its default policy: deny all incoming connections except the allowed ones.
  • The module belongs to the community.general collection, included in the ansible package (Lesson 2.6).

This is a basic lab configuration. Security hardening (SSH, firewall, auditing) is covered in Lesson 9.2, and any security policy for a real environment must be reviewed by a professional.

  1. The complete playbook

This is what webservers.yml looks like:

---
- name: Configure the Aurora Store web servers
  hosts: webservers
  become: true

  tasks:
    - name: Install nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true
        cache_valid_time: 3600

    - name: Create the web root directory
      ansible.builtin.file:
        path: "{{ aurora_web_root }}"
        state: directory
        owner: root
        group: root
        mode: "0755"

    - name: Publish the store home page
      ansible.builtin.copy:
        dest: "{{ aurora_web_root }}/index.html"
        owner: root
        group: root
        mode: "0644"
        content: |
          <!DOCTYPE html>
          <html lang="en">
          <head>
            <meta charset="utf-8">
            <title>Aurora Store - Specialty Coffee</title>
          </head>
          <body>
            <h1>Aurora Store</h1>
            <p>Specialty coffee, roasted every week in small batches.</p>
            <p><small>Served by {{ inventory_hostname }} - {{ aurora_domain }}</small></p>
          </body>
          </html>

    - name: Configure the Aurora site in nginx
      ansible.builtin.copy:
        dest: /etc/nginx/sites-available/aurora
        owner: root
        group: root
        mode: "0644"
        content: |
          # Managed by Ansible (aurora-infra). Do not edit by hand.
          server {
              listen {{ nginx_port }} default_server;
              listen [::]:{{ nginx_port }} default_server;
              server_name {{ aurora_domain }} www.{{ aurora_domain }};

              root {{ aurora_web_root }};
              index index.html;

              location / {
                  try_files $uri $uri/ =404;
              }
          }
      register: nginx_site_config

    - name: Enable the Aurora site
      ansible.builtin.file:
        src: /etc/nginx/sites-available/aurora
        dest: /etc/nginx/sites-enabled/aurora
        state: link
      register: nginx_site_enabled

    - name: Disable the default nginx site
      ansible.builtin.file:
        path: /etc/nginx/sites-enabled/default
        state: absent
      register: nginx_default_site

    - name: Ensure nginx is started and enabled
      ansible.builtin.systemd_service:
        name: nginx
        state: started
        enabled: true

    - name: Reload nginx if its configuration has changed (temporary)
      ansible.builtin.systemd_service:
        name: nginx
        state: reloaded
      when: nginx_site_config.changed or nginx_site_enabled.changed or nginx_default_site.changed

    - name: Allow SSH through the firewall
      community.general.ufw:
        rule: allow
        name: OpenSSH

    - name: Allow HTTP through the firewall
      community.general.ufw:
        rule: allow
        port: "{{ nginx_port }}"
        proto: tcp

    - name: Enable the firewall
      community.general.ufw:
        state: enabled

  1. Before running: --syntax-check, --list-hosts and --list-tasks

Three quick checks that don't touch the servers:

ansible-playbook webservers.yml --syntax-check
playbook: webservers.yml
ansible-playbook webservers.yml --list-hosts
playbook: webservers.yml

  play #1 (webservers): Configure the Aurora Store web servers	TAGS: []
    pattern: ['webservers']
    hosts (2):
      web1
      web2
ansible-playbook webservers.yml --list-tasks
playbook: webservers.yml

  play #1 (webservers): Configure the Aurora Store web servers	TAGS: []
    tasks:
      Install nginx	TAGS: []
      Create the web root directory	TAGS: []
      Publish the store home page	TAGS: []
      Configure the Aurora site in nginx	TAGS: []
      Enable the Aurora site	TAGS: []
      Disable the default nginx site	TAGS: []
      Ensure nginx is started and enabled	TAGS: []
      Reload nginx if its configuration has changed (temporary)	TAGS: []
      Allow SSH through the firewall	TAGS: []
      Allow HTTP through the firewall	TAGS: []
      Enable the firewall	TAGS: []
Option Answers the question Touches the hosts
--syntax-check Is it written correctly? No
--list-hosts Which hosts will it act on? (respects --limit) No
--list-tasks Which tasks will it run, and in what order? No
--check What would change if I run it? Yes, but without modifying anything

--list-tasks is the best way to check that the task names tell an understandable story. Tags (TAGS) are covered in Lesson 5.6.

  1. Running and checking idempotency

Run the playbook:

ansible-playbook webservers.yml

Summarized output of the first run:

PLAY [Configure the Aurora Store web servers] **********************************

TASK [Gathering Facts] *********************************************************
ok: [web1]
ok: [web2]

TASK [Install nginx] ***********************************************************
ok: [web1]
ok: [web2]
...
TASK [Configure the Aurora site in nginx] **************************************
changed: [web1]
changed: [web2]
...
TASK [Reload nginx if its configuration has changed (temporary)] ***************
changed: [web1]
changed: [web2]
...
PLAY RECAP *********************************************************************
web1                       : ok=12   changed=9    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
web2                       : ok=12   changed=9    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

The exact numbers depend on whether you already ran step 1 (in that case, Install nginx shows ok, as here). Now for the decisive test, the second run:

ansible-playbook webservers.yml
...
TASK [Reload nginx if its configuration has changed (temporary)] ***************
skipping: [web1]
skipping: [web2]
...
PLAY RECAP *********************************************************************
web1                       : ok=11   changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0
web2                       : ok=11   changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0

changed=0: the playbook is idempotent. The nginx reload shows up as skipped because no configuration has changed. If you had written it without when:, every run would show changed=1 and reload nginx needlessly: a warning sign you now know how to recognize.

  1. Verifying the result with curl

Ansible saying ok doesn't guarantee that the website works: always verify from the outside. From the control node:

curl -s http://192.168.56.11/
curl -s http://192.168.56.12/ | grep Served
curl -sI http://192.168.56.11/
  <p><small>Served by web2 - aurora-store.example</small></p>
HTTP/1.1 200 OK
Server: nginx/1.24.0 (Ubuntu)
Content-Type: text/html
...

Each server displays its own name. Check the firewall too, with an ad hoc command (the right tool for a query):

ansible webservers -a 'ufw status' -b
web1 | CHANGED | rc=0 >>
Status: active

To                         Action      From
--                         ------      ----
OpenSSH                    ALLOW       Anywhere
80/tcp                     ALLOW       Anywhere
...

In Lesson 3.7 you will add these checks to the playbook itself, with the uri module.

  1. Simulating changes with --check and --diff

You already know --check and --diff from ad hoc commands (Lesson 2.4). In a playbook they are even more valuable, because they simulate the whole set of changes. Change the slogan on the home page in webservers.yml:

            <p>Specialty coffee, roasted every Monday and shipped within 24 hours.</p>

Before applying it, simulate on a single server:

ansible-playbook webservers.yml --check --diff --limit web1
TASK [Publish the store home page] *********************************************
--- before: /var/www/aurora/index.html
+++ after: /home/student/.ansible/tmp/ansible-local-.../tmp...
@@ -6,7 +6,7 @@
 </head>
 <body>
   <h1>Aurora Store</h1>
-  <p>Specialty coffee, roasted every week in small batches.</p>
+  <p>Specialty coffee, roasted every Monday and shipped within 24 hours.</p>
   <p><small>Served by web1 - aurora-store.example</small></p>
 </body>
 </html>

changed: [web1]
...
PLAY RECAP *********************************************************************
web1                       : ok=11   changed=1    unreachable=0    failed=0    skipped=1    ...

The diff shows exactly the line that will change, and the PLAY RECAP predicts a single change. Check with curl -s http://192.168.56.11/ | grep roasted that the page has not changed yet. If the change is what you expected, apply it everywhere:

ansible-playbook webservers.yml --diff

Two warnings about --check:

  • It's a prediction, and it depends on each module supporting check mode (Lesson 2.5). Those that don't support it are skipped.
  • On a new server it may fail: if nginx isn't installed, the simulation of Install nginx doesn't actually install it, and the following tasks (writing to /etc/nginx/... or managing the nginx service) may fail because what they expect doesn't exist. --check is more reliable on servers that are already configured, which is precisely when you need it most: before changing production.

  1. Saving the work in Git

The playbook works, it's idempotent and it has been verified: it's time to commit it.

git add webservers.yml
git commit -m "Web server playbook: nginx, store website and firewall"

Current repository structure:

aurora-infra/
├── ansible.cfg
├── common.yml
├── webservers.yml      ← new
├── inventory/
└── lab/

Common Mistakes and Tips

  • ERROR! couldn't resolve module/action 'community.general.ufw': the collection isn't available. If you installed ansible-core instead of the ansible package, install the collection (ansible-galaxy collection install community.general); formal dependency management arrives in Lesson 6.3.
  • nginx doesn't start after the configuration change: an error in the server block makes the reload fail (Job for nginx.service failed). Diagnose it on the server with ansible web1 -a 'nginx -t' -b. In Module 5 (handlers and templates) you will see how to validate the configuration before applying it.
  • A reload task that always shows changed: the when: is missing, or one of the registered variables doesn't correspond to a configuration task. Remember: actions such as reloaded or restarted are never idempotent on their own.
  • Losing SSH access because of the firewall: it happens if you enable ufw before allowing SSH. In the lab you can recover with vagrant ssh web1 (a console through Vagrant's NAT interface) and sudo ufw disable; on a real server it can be serious. Access rules always go before state: enabled.
  • The website still shows "Welcome to nginx!": the default site is still enabled or nginx hasn't been reloaded. Check the output of the Disable the default nginx site and Reload nginx tasks.
  • Tip: use --limit web1 to test changes on a single server before applying them to all of them. It's the principle behind the rolling deployments you will see in Lesson 5.7.

Exercises

Exercise 1: A status page

Add a task to webservers.yml that publishes {{ aurora_web_root }}/status.html with a simple text that includes the server name. Simulate with --check --diff, apply and verify with curl. Check idempotency.

Exercise 2: Breaking idempotency on purpose

Temporarily remove the when: line from the reload task and run the playbook twice. What does the PLAY RECAP show on the second run? Restore the line when you're done.

Exercise 3: Changing the port without touching the playbook

Without editing webservers.yml, run a simulation with nginx listening on port 8080 on web1 only. Which tasks would change? (Hint: extra variables, -e, have the highest precedence, Lesson 2.2.)

Solutions

Exercise 1. Task added after Publish the store home page:

    - name: Publish the status page
      ansible.builtin.copy:
        dest: "{{ aurora_web_root }}/status.html"
        owner: root
        group: root
        mode: "0644"
        content: |
          <p>{{ inventory_hostname }}: in service</p>
ansible-playbook webservers.yml --check --diff   # predicts changed for that task
ansible-playbook webservers.yml                  # changed=1 per host
ansible-playbook webservers.yml                  # changed=0
curl -s http://192.168.56.11/status.html

There's no need to reload nginx: website files are served as they are; only the configuration requires a reload. You can keep or delete the task; in Lesson 3.6 a more general way of publishing static pages will be defined.

Exercise 2. The second run shows changed=1 on each server (the Reload nginx... task) and skipped=0: the playbook is no longer idempotent, and nginx is reloaded on every run even though nothing has changed. Restore the when: and verify that it goes back to changed=0.

Exercise 3.

ansible-playbook webservers.yml --check --diff --limit web1 -e nginx_port=8080

The tasks that would change are Configure the Aurora site in nginx (the diff shows listen 8080), Reload nginx... (no longer skipped, because the configuration would change) and Allow HTTP through the firewall (a new rule for 8080). Don't apply it: Aurora's official port is the one in group_vars/webservers.yml.

Conclusion

You have written, step by step, Aurora Store's first real playbook: webservers.yml installs nginx, publishes the store page in {{ aurora_web_root }}, configures and enables the Aurora site, ensures the service is started and enabled, reloads nginx only when its configuration changes (temporarily, until handlers) and enables the firewall with community.general.ufw. You have followed the professional workflow: --syntax-check, --list-hosts, --list-tasks, simulation with --check --diff, execution, idempotency test, verification with curl and commit. Aurora now has two playbooks and will soon have more. In the next lesson, Playbook Structure, you will learn the full anatomy of a playbook: several plays in one file, all the play and task keywords, the execution order, and how to organize Aurora's playbooks with a site.yml that brings them all together, including the new PostgreSQL playbook for db1.

Ansible Course: From Beginner to Advanced

Module 1: Introduction to Ansible

Module 2: Ansible Fundamentals

Module 3: Playbooks

Module 4: Roles

Module 5: Advanced Playbook Techniques

Module 6: Ansible Galaxy

Module 7: Ansible Tower, AWX and Automation Platform

Module 8: Ansible for DevOps

Module 9: Ansible Best Practices

Module 10: Advanced Ansible Topics

Module 11: Final Project

© Copyright 2026. All rights reserved