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
- What we are going to build
- Step 1: the play skeleton and installing nginx
- Step 2: the website directory and the home page
- Step 3: the Aurora site in nginx
- Step 4: the nginx service
- Step 5: the firewall with
community.general.ufw - The complete playbook
- Before running:
--syntax-check,--list-hostsand--list-tasks - Running and checking idempotency
- Verifying the result with
curl - Simulating changes with
--checkand--diff - Saving the work in Git
- 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:
- 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: 3600hosts: webservers: onlyweb1andweb2.become: true: installing packages and writing to/etcrequiresroot.update_cache: truewithcache_valid_time: 3600: updates the package list (apt update) only if it's more than an hour old. Withoutcache_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:
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.
- 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>filewithstate: directorycreates the directory if it doesn't exist (and with the given permissions); if it already exists with those permissions, it does nothing.copywithcontent: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 thedeployuser exists in code (Lesson 3.6), the directory will become its property.
For more complex pages or configurations,
copywithcontent:falls short. In Lesson 5.2 you will learn to use Jinja2 templates with thetemplatemodule. For now,content:is perfect.
- 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.
filewithstate: linkcreates the symbolic linkdestpointing tosrc.filewithstate: absentremoves the link to the default site (the original file stays insites-available/, in case you ever need it).listen ... default_servermakes our site answer any request, including those addressed to the IP. That's why thedefaultsite has to be disabled: twodefault_serversites 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.
- 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: reloadedreloads nginx every time it runs. That's why we addwhen:, 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 asskipping.
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.
- Step 5: the firewall with
community.general.ufw
community.general.ufwUbuntu 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: enabledname: OpenSSHuses the application profile installed by the SSH server package (port 22/tcp).port: "{{ nginx_port }}"opens the port from the inventory variable (80).state: enabledenablesufwwith its default policy: deny all incoming connections except the allowed ones.- The module belongs to the
community.generalcollection, included in theansiblepackage (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.
- 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
- Before running:
--syntax-check, --list-hosts and --list-tasks
--syntax-check, --list-hosts and --list-tasksThree quick checks that don't touch the servers:
playbook: webservers.yml
play #1 (webservers): Configure the Aurora Store web servers TAGS: []
pattern: ['webservers']
hosts (2):
web1
web2playbook: 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.
- Running and checking idempotency
Run the playbook:
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=0The 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:
...
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=0changed=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.
- Verifying the result with
curl
curlAnsible 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/Each server displays its own name. Check the firewall too, with an ad hoc command (the right tool for a query):
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.
- Simulating changes with
--check and --diff
--check and --diffYou 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:
Before applying it, simulate on a single server:
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:
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 nginxdoesn't actually install it, and the following tasks (writing to/etc/nginx/...or managing thenginxservice) may fail because what they expect doesn't exist.--checkis more reliable on servers that are already configured, which is precisely when you need it most: before changing production.
- Saving the work in Git
The playbook works, it's idempotent and it has been verified: it's time to commit it.
Current repository structure:
Common Mistakes and Tips
ERROR! couldn't resolve module/action 'community.general.ufw': the collection isn't available. If you installedansible-coreinstead of theansiblepackage, 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
serverblock makes the reload fail (Job for nginx.service failed). Diagnose it on the server withansible 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: thewhen:is missing, or one of the registered variables doesn't correspond to a configuration task. Remember: actions such asreloadedorrestartedare never idempotent on their own. - Losing SSH access because of the firewall: it happens if you enable
ufwbefore allowing SSH. In the lab you can recover withvagrant ssh web1(a console through Vagrant's NAT interface) andsudo ufw disable; on a real server it can be serious. Access rules always go beforestate: enabled. - The website still shows "Welcome to nginx!": the
defaultsite is still enabled or nginx hasn't been reloaded. Check the output of theDisable the default nginx siteandReload nginxtasks. - Tip: use
--limit web1to 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.htmlThere'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.
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
- What Is Ansible?
- Installing Ansible
- Setting Up the Practice Lab
- Ansible Architecture
- Basic Ansible Commands
Module 2: Ansible Fundamentals
- Inventory Files
- Inventory Variables: group_vars and host_vars
- Configuring Ansible (ansible.cfg)
- Ad Hoc Commands
- Ansible Modules
- Collections and Fully Qualified Names (FQCN)
Module 3: Playbooks
- Introduction to Playbooks
- Essential YAML for Ansible
- Writing Your First Playbook
- Playbook Structure
- Variables and Facts
- Conditionals and Loops
- Registering Results and Debugging Playbooks
Module 4: Roles
- Introduction to Roles
- Creating Roles
- Role Directory Structure
- Using Roles in Playbooks
- Reusing Tasks: include and import
- Role Dependencies and Argument Validation
Module 5: Advanced Playbook Techniques
- Handlers
- Jinja2 Templates
- Filters and Lookups
- Ansible Vault
- Error Handling
- Tags and Selective Execution
- Rolling Deployments and Delegation
- Optimizing Playbooks
Module 6: Ansible Galaxy
- What Is Ansible Galaxy?
- Using Ansible Galaxy
- Managing Dependencies with requirements.yml
- Creating and Sharing Roles
- Creating Your Own Collections
Module 7: Ansible Tower, AWX and Automation Platform
- Introduction to Ansible Tower and AWX
- Installing AWX
- Using AWX: Job Templates and Jobs
- Managing Projects and Inventories
- Credentials, Permissions (RBAC) and Workflows
- Execution Environments and ansible-navigator
Module 8: Ansible for DevOps
- Ansible and Docker
- Ansible and Kubernetes
- CI/CD with Ansible
- Ansible in Cloud Environments
- Ansible and Terraform
Module 9: Ansible Best Practices
- Code Organization
- Security Best Practices
- Performance Tuning
- Code Quality: ansible-lint and yamllint
- Testing Ansible Code with Molecule
Module 10: Advanced Ansible Topics
- Custom Modules
- Dynamic Inventory
- Ansible Plugins
- The Ansible API and ansible-runner
- Event-Driven Ansible
