Ansible Series

🗂️ The Top 1% Hands-On for Real-World Config Management With Ansible Roles, Handlers, and Templates

Introduction

This article is part of the Top 1% Series’ full article guide. It reuses the control/node1 environment from the previous hands-on as-is.

Prerequisites

The Big Picture

This hands-on consists of four steps.

graph LR
    Step1["Step1<br/>Scaffold a role"]
    Step2["Step2<br/>Distribute a config file with<br/>variables and a template"]
    Step3["Step3<br/>Restart only on change,<br/>via a handler"]
    Step4["Step4<br/>Run it and confirm idempotency<br/>and handler firing"]
    Step1 --> Step2 --> Step3 --> Step4

Hands-On Steps

Step 1: Scaffold a role

In the ~/ansible-lab directory from before, use the ansible-galaxy command to auto-generate the standard directory structure for a role.

cd ~/ansible-lab
mkdir roles
ansible-galaxy init roles/webserver

Check the generated directory structure with the tree command. Install it first if it isn’t already there.

sudo apt update
sudo apt install -y tree
tree roles/webserver
roles/webserver/
├── tasks/main.yml       # The Tasks this role actually runs
├── handlers/main.yml    # Handlers (run only when something changed)
├── templates/           # Jinja2 templates (empty for now)
├── vars/main.yml        # Variables specific to this role
├── defaults/main.yml    # Default values for variables (lower priority than vars)
└── (other directories, unused today)

tree displays a directory’s hierarchy visually, laid out just like a diagram. Instead of running ls on each directory in turn, this one command lets you take in a role’s entire shape at a glance.

Notice how “tasks,” “handlers,” “templates,” and “variables” each get their own dedicated directory and file. In the previous hands-on, all of this was crammed into a single file, site.yml. A role is a mechanism for organizing that mess, so that “building a webserver” becomes a self-contained unit you can copy straight into another project and reuse.

Step 2: Distributing a config file with variables and a template

First, pull out the values you’ll want to change per environment as variables. Edit roles/webserver/vars/main.yml.

nano roles/webserver/vars/main.yml
server_name: lab.example.com
welcome_message: "Hello from Ansible Roles!"

Variables themselves should already feel familiar, from the -e option in earlier hands-on labs.

Next, create an Nginx test page with these variables embedded, as a Jinja2 template at roles/webserver/templates/index.html.j2.

nano roles/webserver/templates/index.html.j2
<h1>{{ welcome_message }}</h1>
<p>server_name: {{ server_name }}</p>

The parts wrapped in {{ }} are Jinja2’s variable-expansion syntax — they get replaced with the values from vars/main.yml at runtime. This lets one single template file produce a different config file per environment, just by changing the values in vars/main.yml. Jinja2 itself is a templating engine widely used across the Python world, and Ansible adopts it as-is. Don’t overthink it — the one thing to remember is that “wherever you write {{ variable_name }}, it gets replaced with the actual value at runtime.” That understanding will click naturally as you work through the rest of these steps.

Next, edit roles/webserver/tasks/main.yml to describe installing Nginx and deploying this template.

nano roles/webserver/tasks/main.yml
---
- name: Install Nginx
  ansible.builtin.apt:
    name: nginx
    state: present
    update_cache: true

- name: Deploy the test page from the template
  ansible.builtin.template:
    src: index.html.j2
    dest: /var/www/html/index.html
  notify: Restart Nginx

Notice we’re using the ansible.builtin.template module here, in place of the ansible.builtin.copy module from the previous hands-on. copy transfers a static file as-is, while template expands the Jinja2 {{ }} syntax inside the file at runtime, before distributing it.

Step 3: Restart a service “only when something changed,” with a handler

The notify: Restart Nginx at the end of that Task is what triggers a handler. Edit roles/webserver/handlers/main.yml to define the corresponding handler.

nano roles/webserver/handlers/main.yml
---
- name: Restart Nginx
  ansible.builtin.service:
    name: nginx
    state: restarted

A handler looks almost identical to an ordinary Task, but there’s one decisive difference: it never runs unless it’s called. An ordinary Task always runs, in the order it’s written in the Playbook, while a handler is a more reserved kind of entity — it only runs when some Task names it via notify, and even then, only when that Task actually changed something. This combination of notify and handlers plays an extremely important role in real-world Ansible code. A Task using the template module only returns a changed result — and only in that case does it call the handler named in notify — when the destination file’s contents actually change. If the contents didn’t change (on a second or later run, for example), the handler is never called, and Nginx isn’t restarted. This prevents the wasteful, real-world-undesirable behavior of unconditionally restarting a service every single time a config file is distributed.

Step 4: Run the role from site.yml

Rewrite ~/ansible-lab/site.yml to a simple form that just calls the role.

nano site.yml
---
- name: Build the web server (role version)
  hosts: webservers
  become: true
  roles:
    - webserver

Run it. As in the previous hands-on, add -K to have it prompt for the sudo password.

ansible-playbook -i inventory.ini site.yml -K

On the first run, installing Nginx and deploying the template (and the resulting Nginx restart triggered by the handler) should both be reported as changed. Run the same Playbook again. This time, since the template’s content hasn’t changed, the template Task is reported as ok, and the handler named in notify is never called — Nginx isn’t restarted.

Next, change the value of welcome_message in vars/main.yml, and run it once more. This time the template Task is reported as changed, and you can confirm from the PLAY RECAP output that the handler is actually called, and Nginx is restarted.

What a Pro Sees Here (Top 1% Understanding)

Why real-world Ansible code is organized around roles, not a single Playbook

Writing everything into one site.yml, as in the previous hands-on, is no problem for a small automation targeting only Nginx. But in practice, it’s normal to manage multiple different server roles simultaneously — web servers, database servers, load balancers, and more. Splitting things into role units makes it possible to manage and reuse each role independently — copying just the webserver role into a separate project, or handing off just the dbserver role to a different team member. On top of that, Ansible Galaxy hosts a huge library of ready-made roles published by engineers worldwide, so you often don’t have to reinvent the wheel at all.

How a handler runs “just once, gathered at the end”

A handler has one more important property. Even if multiple Tasks in the same Play notify the same handler, that handler still runs just once, gathered at the end of the Play. For example, if three separate Tasks distributing three different Nginx config files all specify the same notify: Restart Nginx, Nginx is only restarted once at the end of the Play (as long as at least one of them changed) — not three separate times. This is a genuinely sensible design in practice: batch up multiple config changes, then restart the service safely, exactly once.

Common Misconceptions and Pitfalls

Troubleshooting Perspective

  1. You changed the config file and re-ran it, but the service didn’t restart: Check whether notify is correctly specified on the Task, and whether the string given to notify exactly matches the name in handlers/main.yml (even a one-character mismatch is silently treated as a different, nonexistent handler).
  2. A template-module Task outputs the literal {{ }} instead of expanding the variable: Check for a typo in the variable name, or whether you’re referencing a variable that isn’t defined in vars/main.yml.
  3. An error says the role can’t be found: Check that the directory you’re running site.yml from is positioned correctly relative to the roles directory (Ansible looks for roles/ relative to ansible.cfg’s location or the current working directory at runtime).

Summary

Takeaways to Apply Today

  1. When writing a Task that requires restarting a service, make it a habit to reach for the notify-plus-handler combination instead of restarting unconditionally.
  2. If you get the chance to write a Playbook for a second web server use case, try copying and reusing the webserver role you just built as-is.

References

Comments

Feel free to leave thoughts, questions, or corrections below (sign in with a GitHub account to comment or react).