At the end of Module 4, the Aurora Store roles were clean and well organized, except for three tasks marked "(temporary)": the nginx reload, with a condition that combines four registered variables, the PostgreSQL restart when its parameters change, and its reload when pg_hba.conf changes. All three solve the same problem, "do this only if something has changed", and all three solve it badly: they force you to register results, maintain conditions by hand and place the task in exactly the right spot. Ansible has a tool designed precisely for this: handlers. In this lesson you'll learn what they are, how they're notified, when and how many times they run, how to group them with listen, how to run them early with meta: flush_handlers, what happens to them when something fails, and how to validate the nginx configuration before reloading it. By the end, the three temporary tasks will be gone from the Aurora roles.

  1. The problem with the temporary tasks

Remember how roles/nginx/tasks/service.yml ended up in Lesson 4.5:

- name: Reload nginx if its configuration has changed (temporary)
  ansible.builtin.systemd_service:
    name: "{{ nginx_service }}"
    state: reloaded
  when: >-
    nginx_gzip_config is changed or
    nginx_site_config is changed or
    nginx_site_enabled is changed or
    nginx_default_site is changed

It works, but it has several flaws:

Flaw Consequence
Every configuration task needs a register Registered variables that exist only to feed a condition
The condition lists every variable by hand If you add a configuration task and forget to add it here, nginx won't be reloaded
The task depends on its position It has to go after every task that can change the configuration
The pattern is repeated for every service PostgreSQL has two more tasks just like it, and every new role would bring more
There's no protection against several changes If two files change at different points in the role, you'd have to decide where to reload

What you really want to express is something else: "if this task changes something, it must trigger an nginx reload; do it once, when you've finished". That's a handler.

  1. What a handler is

A handler is a normal task (with its module and its parameters) with two differences:

  • It doesn't run in its turn: it's declared separately, in the handlers: section of a play or in the handlers/ directory of a role.
  • It runs only if some task notifies it, and a task only notifies when its result is changed.

A minimal example, in a test playbook that isn't part of Aurora:

---
# demo-handlers.yml (for testing only: delete it afterwards)
- name: Demonstrate how handlers work
  hosts: web1
  become: true

  tasks:
    - name: Publish a test file
      ansible.builtin.copy:
        dest: /tmp/demo-handler.txt
        content: "Version 1\n"
        mode: "0644"
      notify: Report the change

  handlers:
    - name: Report the change
      ansible.builtin.debug:
        msg: "The test file has changed on {{ inventory_hostname }}"
  • notify: Report the change says which handler to notify. The value is the handler's name (or a topic, section 5).
  • The handlers: section has the same shape as tasks:: a list of tasks with name and a module.

Run it twice:

ansible-playbook demo-handlers.yml
ansible-playbook demo-handlers.yml

First run:

TASK [Publish a test file] *****************************************************
changed: [web1]

RUNNING HANDLER [Report the change] ********************************************
ok: [web1] =>
    msg: The test file has changed on web1

Second run:

TASK [Publish a test file] *****************************************************
ok: [web1]

PLAY RECAP *********************************************************************
web1                       : ok=2    changed=0    unreachable=0    failed=0    ...

On the second run the file already existed with that content: the task returns ok, doesn't notify, and the handler doesn't appear. Notice that the output tells them apart: normal tasks appear as TASK, handlers as RUNNING HANDLER.

  1. notify: when and how many times a handler runs

There are only a few execution rules, but it pays to know them precisely:

Rule Detail
Only on changed A task notifies if its result is changed. With ok, skipped or failed it doesn't notify
At the end of the section Notified handlers run when the play section in which they were notified finishes, not immediately
Only once Even if ten tasks notify the same handler, it runs once per host at each execution point
Per host It runs only on the hosts where some task notified it
Definition order They run in the order in which they're written in handlers, not in the order in which they were notified
Loops A task with loop notifies once if any of its iterations changes

What does "at the end of the section" mean? In Lesson 4.4 you saw the full order of a play. Pending handlers run at three points:

flowchart TD
    A[Fact gathering] --> B[pre_tasks]
    B --> H1[Handlers notified in pre_tasks]
    H1 --> C[roles]
    C --> D[tasks]
    D --> H2[Handlers notified in roles and tasks]
    H2 --> E[post_tasks]
    E --> H3[Handlers notified in post_tasks]

This has an important consequence for Aurora: in dbservers.yml, the PostgreSQL restart (notified inside the role) will run before the post_tasks, so the postgresql_ping check will see the server already restarted. And in webservers.yml, the nginx reload will happen before the post_tasks check the website.

The definition order rule often surprises people. With these handlers:

  handlers:
    - name: Step A
      ansible.builtin.debug:
        msg: A
    - name: Step B
      ansible.builtin.debug:
        msg: B

if one task notifies Step B and a later one notifies Step A, the output shows Step A first and then Step B. You'll take advantage of this in section 6: the order of the handlers in the file is a tool for chaining actions.

  1. Handlers in roles: handlers/main.yml

In a role, handlers go in handlers/main.yml, the directory you were introduced to in Lesson 4.3 and which you hadn't created until now. The format is a list of tasks, just like tasks/main.yml:

roles/nginx/
├── handlers/
│   └── main.yml      ← the role's handlers
├── tasks/
│   └── ...           ← the tasks notify them by name
└── ...

Important details:

  • The role's tasks notify the handlers by name, just as in a play.
  • Role handlers are added to the play's: a notify in a task in the playbook's post_tasks can also notify a handler of a role applied in that play.
  • If two roles in the same play define a handler with the same name, there's a conflict (only one of them will respond to the notification). That's why names should include the service: "Reload nginx", not "Reload".
  • If you need to be explicit, you can notify with the role prefix: notify: "nginx : Reload nginx".
  • Handler files can be split with import_tasks inside handlers/main.yml. With import_tasks, each imported handler can be notified by its name; with include_tasks, you notify the inclusion and the whole file runs (you saw this coming in the table in Lesson 4.5). In Aurora the handler files are short and aren't split.

  1. Notifying several handlers and grouping them with listen

5.1. Several notify entries

notify accepts a list:

- name: Publish the site certificate
  ansible.builtin.copy:
    src: store.crt
    dest: /etc/ssl/certs/store.crt
    mode: "0644"
  notify:
    - Reload nginx
    - Notify the operations team

If the task changes, both handlers become pending. Each will run once, in its definition order.

5.2. Topics with listen

Sometimes you want several actions to respond to the same event, without the task having to know about all of them. For that, a handler can declare listen: the name of a topic it subscribes to.

handlers:
  - name: Restart the application
    ansible.builtin.systemd_service:
      name: aurora-api
      state: restarted
    listen: Store configuration changed

  - name: Flush the cache
    ansible.builtin.command:
      cmd: /usr/local/bin/aurora-cache-flush
    listen: Store configuration changed

A task with notify: Store configuration changed triggers both. The example is illustrative (Aurora doesn't have an API or a cache yet), but it shows the advantage: the task announces what happened and the handlers decide what to do. If tomorrow a third action is needed, you add another handler with the same listen without touching any task.

Form The task notifies… What runs…
By name notify: Reload nginx The handler with that name
By topic notify: Configuration changed Every handler with that listen
List notify: [A, B] Handlers A and B

listen also accepts a list of topics (listen: [topic1, topic2]), and a handler with listen can still be notified by its name.

  1. Validating before reloading

Reloading a service with a broken configuration is dangerous. With nginx in particular, systemctl reload nginx fails if the configuration has a syntax error, but the error ends up in the journal, with an unclear message in the Ansible output, and in a run with many servers it can go unnoticed. The right tool is nginx -t, which checks the whole configuration without applying anything:

ssh web1 'sudo nginx -t'
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

There are two ways to integrate validation into Ansible:

Technique How it works When it's useful
The validate: parameter of copy/template The new file is written to a temporary file and validated before it's put in place. If validation fails, the original file isn't touched When the file can be validated on its own (a complete nginx.conf, sudoers, sshd_config)
A validation handler before the reload One handler runs nginx -t and, only if it passes, another handler reloads When the file is a fragment that only makes sense within the complete configuration (a site in sites-available, a file in conf.d)

The files the nginx role manages today are fragments: conf.d/gzip.conf and the site in sites-available. nginx -t -c file is no good for validating them, because an isolated server { ... } block isn't a complete nginx configuration. For them, the technique is the second one: two handlers chained by definition order and subscribed to the same topic.

- name: Validate the nginx configuration
  ansible.builtin.command:
    cmd: nginx -t
  changed_when: false
  listen: Reload nginx

- name: Apply the nginx reload
  ansible.builtin.systemd_service:
    name: nginx
    state: reloaded
  listen: Reload nginx
  • The tasks notify the Reload nginx topic, which triggers both handlers.
  • They run in definition order: validation first.
  • If nginx -t fails, the host is marked as failed and the second handler doesn't run on that host: nginx keeps running with the previous configuration, which it has loaded in memory, and the syntax error shows up clearly in the Ansible output.
  • changed_when: false because checking the configuration doesn't change anything (Lesson 3.7).

In Lesson 5.2, when you move the configuration to templates, you'll also manage the complete nginx.conf, and that file you will validate with validate:.

  1. Practice: the nginx role handlers

Create the directory and the handlers file:

mkdir roles/nginx/handlers

roles/nginx/handlers/main.yml:

---
# Handlers of the nginx role.
# Tasks notify the "Reload nginx" topic: first the complete configuration
# is validated and, only if it's correct, the service is reloaded.

- name: Validate the nginx configuration
  ansible.builtin.command:
    cmd: nginx -t
  changed_when: false
  listen: Reload nginx

- name: Apply the nginx reload
  ansible.builtin.systemd_service:
    name: "{{ nginx_service }}"
    state: reloaded
  listen: Reload nginx

The handlers use the same internal variables as the tasks (nginx_service, from vars/main.yml).

Now change the tasks so that they notify instead of registering. roles/nginx/tasks/configure.yml:

---
- name: Publish the gzip compression configuration
  ansible.builtin.copy:
    src: gzip.conf
    dest: "{{ nginx_conf_d_dir }}/gzip.conf"
    owner: root
    group: root
    mode: "0644"
  notify: Reload nginx

roles/nginx/tasks/site.yml (the site content doesn't change; only the three register lines are replaced with notify):

---
- name: Configure the site in nginx
  ansible.builtin.copy:
    dest: "{{ nginx_sites_available_dir }}/{{ nginx_site_name }}"
    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 {{ nginx_server_name }};

          root {{ nginx_root }};
          index index.html;

          location / {
              try_files $uri $uri/ =404;
          }
      }
  notify: Reload nginx

- name: Enable the site
  ansible.builtin.file:
    src: "{{ nginx_sites_available_dir }}/{{ nginx_site_name }}"
    dest: "{{ nginx_sites_enabled_dir }}/{{ nginx_site_name }}"
    state: link
  notify: Reload nginx

- name: Disable the default nginx site
  ansible.builtin.file:
    path: "{{ nginx_sites_enabled_dir }}/default"
    state: absent
  when: nginx_remove_default_site
  notify: Reload nginx

And roles/nginx/tasks/service.yml is left with just the task that ensures the service, as announced in Lesson 4.5:

---
- name: Ensure nginx is started and enabled
  ansible.builtin.systemd_service:
    name: "{{ nginx_service }}"
    state: started
    enabled: true

Compare before and after:

Before (temporary) After (handlers)
4 registered variables (nginx_gzip_config, nginx_site_config, nginx_site_enabled, nginx_default_site) None
Four-line >- condition No condition
The reload had to go after all the configuration tasks The order of the tasks doesn't matter: the reload happens at the end
Adding a configuration file meant touching the condition Just add notify: Reload nginx to the new task
No validation nginx -t before every reload

  1. Practice: the postgresql role handlers

PostgreSQL needs two different actions:

  • Restart when parameters such as listen_addresses, port or shared_buffers change, since they're only applied when the server starts.
  • Reload when pg_hba.conf changes, which PostgreSQL re-reads without dropping connections.

Create roles/postgresql/handlers/main.yml:

mkdir roles/postgresql/handlers
---
# Handlers of the postgresql role.

# Required for the parameters that are only applied at startup
# (listen_addresses, port, shared_buffers, max_connections).
- name: Restart PostgreSQL
  ansible.builtin.systemd_service:
    name: "{{ postgresql_service }}"
    state: restarted

# Enough for pg_hba.conf: it's re-read without dropping connections.
- name: Reload PostgreSQL
  ansible.builtin.systemd_service:
    name: "{{ postgresql_service }}"
    state: reloaded

The order is deliberate: if the parameters and the access control both change in the same run, both are notified, and the restart will run first and then the reload (which, after a restart, is harmless).

roles/postgresql/tasks/access.yml loses its temporary task:

---
- name: Allow the clients to access the database
  community.postgresql.postgresql_pg_hba:
    dest: "{{ postgresql_config_dir }}/pg_hba.conf"
    contype: host
    databases: "{{ postgresql_hba_database }}"
    users: "{{ postgresql_hba_user }}"
    address: "{{ item }}/32"
    method: "{{ postgresql_hba_method }}"
    state: present
  loop: "{{ postgresql_hba_clients }}"
  notify: Reload PostgreSQL

The task has a loop: if the rule for just one client is added, it still notifies (and the reload happens once, not once per client).

What about configure.yml? There's a subtlety there that deserves its own section.

  1. Running handlers early: meta: flush_handlers

Look at the order of the postgresql role phases: install.yml → configure.yml → users.yml → access.yml. With a handler, the restart caused by a parameter change would happen at the end of the role (actually, at the end of the play's roles and tasks section). But users.yml connects to PostgreSQL to create users and databases, and it does so before that restart, with the old configuration still active.

Does it matter? With the current parameters, hardly ever. But imagine you change postgresql_port from 5432 to 5433. The tasks in users.yml should connect to the new port, which doesn't exist yet because the server hasn't been restarted. In fact, reviewing this case reveals a small bug in the role: the tasks in users.yml don't specify the port, so the community.postgresql modules always use 5432, the default value. Fix it while you're at it in roles/postgresql/tasks/users.yml:

---
- name: Create the PostgreSQL users
  community.postgresql.postgresql_user:
    name: "{{ item.name }}"
    port: "{{ postgresql_port }}"
    state: present
  become_user: postgres
  loop: "{{ postgresql_users }}"
  loop_control:
    label: "{{ item.name }}"

- name: Create the databases
  community.postgresql.postgresql_db:
    name: "{{ item.name }}"
    owner: "{{ item.owner }}"
    port: "{{ postgresql_port }}"
    state: present
  become_user: postgres
  loop: "{{ postgresql_databases }}"
  loop_control:
    label: "{{ item.name }}"

Now, for these tasks to find the server on the new port, the restart has to happen between configure.yml and users.yml. The tool is ansible.builtin.meta: flush_handlers, a special task that runs all pending handlers at that moment. roles/postgresql/tasks/configure.yml ends up like this:

---
- name: Configure the PostgreSQL parameters
  ansible.builtin.copy:
    dest: "{{ postgresql_config_dir }}/conf.d/{{ postgresql_conf_name }}.conf"
    owner: postgres
    group: postgres
    mode: "0644"
    content: |
      # Managed by Ansible (aurora-infra). Do not edit by hand.
      listen_addresses = '{{ postgresql_listen_addresses }}'
      port = {{ postgresql_port }}
      max_connections = {{ postgresql_max_connections }}
      shared_buffers = {{ postgresql_shared_buffers }}
  notify: Restart PostgreSQL

- name: Ensure PostgreSQL is started and enabled
  ansible.builtin.systemd_service:
    name: "{{ postgresql_service }}"
    state: started
    enabled: true

- name: Apply pending restarts now
  ansible.builtin.meta: flush_handlers

How flush_handlers works:

  • It runs the handlers notified up to that point, on every host in the play that has them pending, and marks them as run.
  • If they're notified again later (for example, Reload PostgreSQL from access.yml), they'll run again at the end of the section.
  • If nothing is pending, it does nothing (it doesn't show up as a change).
  • It's a meta: an instruction for the Ansible engine itself, which doesn't run on the server. Conditions (when) on meta tasks have limited support that varies between versions; use it without conditions.

Use it sparingly: every flush_handlers breaks the "only once at the end" rule. It's justified when a later task needs the change to be applied already, as here.

Does every register + when become a handler?

No. The common role has a similar pattern:

- name: Re-read the local facts if they have changed
  ansible.builtin.setup:
    filter: ansible_local
  when: common_local_facts is changed

This task stays as it is. Its effect (updating ansible_local in memory) must happen right after the facts are published, so that any later task in the play sees the new values. A handler would delay it to the end of the section, and with a flush_handlers right after it the result would be the same with more moving parts. Rule of thumb:

Situation Tool
An action on a service (reload, restart) after a configuration change Handler
An action that must happen immediately and that the following tasks use Task with when: ... is changed
A service action that the following tasks need already applied Handler + meta: flush_handlers

  1. Handlers and failures: --force-handlers and force_handlers

This is the behavior that surprises people most. Suppose that, on web1:

  1. "Configure the site in nginx" changes the file and notifies Reload nginx.
  2. Later, "Allow HTTP through the firewall" fails (for example, because of an apt or ufw lock).

By default, when a host fails, its pending handlers don't run. nginx keeps the old configuration loaded. And the worst comes on the next run: the site file is already on disk with the correct content, the task returns ok, doesn't notify… and the reload never happens. The server is left with a configuration on disk that differs from the one it's using, without Ansible noticing.

sequenceDiagram
    participant A as Ansible
    participant W as web1
    A->>W: Configure the site (changed) → notifies Reload nginx
    A->>W: Allow HTTP (FAILED)
    Note over A,W: Failed host: pending handlers are discarded
    A->>W: 2nd run: Configure the site (ok, no notification)
    Note over W: nginx keeps the old configuration

The solution is to ask Ansible to run the notified handlers even if the host fails:

Form Scope
ansible-playbook site.yml --force-handlers That run
force_handlers: true in the play That play
force_handlers = True in the [defaults] section of ansible.cfg The whole project

With force_handlers, pending handlers run on the failed hosts at the end of the play (not on unreachable ones: without a connection, there's nothing to be done). In Aurora, where the nginx handlers validate before reloading, forcing is safe: if the failure had left an invalid configuration, nginx -t would detect it and the reload wouldn't happen. Add it to ansible.cfg, in [defaults], after retry_files_enabled:

# Run notified handlers even if a later task fails on the host.
# Prevents a configuration change from being left on disk without being applied.
force_handlers = True

Keep the other side in mind: with PostgreSQL there's no prior validation, and a forced restart with an invalid parameter would leave the database stopped. That's another reason to test changes in the lab (and, later on, in staging) before taking them to production.

Two more behaviors worth knowing:

  • Check mode: tasks that "would change" notify, and handlers also run in simulation (the output shows changed without touching the service). This way --check accurately reflects which reloads would happen.
  • If a handler fails, the host is marked as failed just like with any task. With nginx -t, that's exactly what you want.

  1. Names and best practices

Practice Reason
Unique names that include the service ("Reload nginx", "Restart PostgreSQL") The handlers of all the roles in a play share a namespace
Names without variables (Reload {{ service }}) The name is resolved before many variables exist; notifications may not find it
Capitalized and in the imperative, like tasks Aurora convention (Lesson 3.4)
Prefer reloaded to restarted when the service supports it A reload doesn't drop connections
Validate before reloading when a tool exists (nginx -t, apachectl configtest, sshd -t) Avoids applying broken configurations
Use listen when several actions respond to the same event Tasks announce the event; handlers decide what to do
Don't use handlers for logic that must happen immediately For that, use when: ... is changed or flush_handlers
Notify from idempotent tasks A command without changed_when would notify on every run

  1. Verifying and saving the work

Check that there are no temporary tasks or old registered variables left:

grep -rn -e temporary -e nginx_gzip_config -e nginx_site_config \
  -e nginx_site_enabled -e nginx_default_site -e postgresql_config -e postgresql_hba roles/

The only possible match is postgresql_config_dir, which is a different variable (the configuration path). Apply the infrastructure:

ansible-playbook site.yml
PLAY RECAP *********************************************************************
db1                        : ok=...  changed=0    unreachable=0    failed=0    ...
web1                       : ok=...  changed=0    unreachable=0    failed=0    ...
web2                       : ok=...  changed=0    unreachable=0    failed=0    ...

changed=0 and no RUNNING HANDLER: the files haven't changed, so nobody has notified anything. To see the handlers in action, cause some drift on web1 by adding a line to the site by hand:

ansible web1 -b -m ansible.builtin.lineinfile \
  -a "path=/etc/nginx/sites-available/aurora line='# manual change'"
ansible-playbook webservers.yml --limit web1
TASK [nginx : Configure the site in nginx] *************************************
changed: [web1]
...
RUNNING HANDLER [nginx : Validate the nginx configuration] *********************
ok: [web1]

RUNNING HANDLER [nginx : Apply the nginx reload] *******************************
changed: [web1]
...
PLAY RECAP *********************************************************************
web1                       : ok=...  changed=2    unreachable=0    failed=0    ...

Ansible has restored the file, validated the configuration and reloaded nginx, and the handlers ran before the post_tasks that check the website. Delete the test playbook from section 2 and the file it created, and save the work:

rm demo-handlers.yml
ansible web1 -b -m ansible.builtin.file -a "path=/tmp/demo-handler.txt state=absent"
git add ansible.cfg roles/
git commit -m "Handlers in nginx and postgresql instead of the temporary tasks"

Common Mistakes and Tips

  • "The requested handler 'X' was not found in either the main handlers list nor in the listening handlers list": the notify name doesn't exactly match any name or listen (capitalization, accents and spaces all count). Copy and paste the name.
  • Expecting the handler to run right after the task: it runs at the end of the section. If a later task needs the change applied, use meta: flush_handlers.
  • A configuration on disk that never gets applied: a later failure prevented the handler from running, and on subsequent runs the task no longer changes. Use force_handlers and, if you suspect it has happened, reload the service by hand or with an ad hoc command.
  • A command that notifies on every run: command and shell always return changed unless you use changed_when. A handler notified that way always runs.
  • Two roles with a "Restart" handler: only one responds. Include the name of the service.
  • Putting when on the handler to "filter" the notification: it works, but it usually means the notification is badly designed. The condition should be on the task that notifies.
  • Tip: when you review a role, look for register: lines followed by when: ... is changed on a service. They're almost always handlers in disguise.

Exercises

Exercise 1: Predict the output

Given this play (don't run it yet), which RUNNING HANDLER lines will appear, and in what order, on the first run? And on the second?

- name: Handlers exercise
  hosts: web1
  become: true
  tasks:
    - name: File one
      ansible.builtin.copy:
        dest: /tmp/one.txt
        content: "1\n"
      notify: Second
    - name: File two
      ansible.builtin.copy:
        dest: /tmp/two.txt
        content: "2\n"
      notify: [First, Second]
    - name: Query
      ansible.builtin.command:
        cmd: date
      notify: First
  handlers:
    - name: First
      ansible.builtin.debug:
        msg: First
    - name: Second
      ansible.builtin.debug:
        msg: Second

Exercise 2: A topic for the store

Modify the play from Exercise 1 so that the first two tasks notify a single topic, Files changed, which both handlers listen to. Does the execution order change?

Exercise 3: The silent failure

Without force_handlers, on web2 the task "Publish the gzip compression configuration" changes and, afterwards, a firewall task fails. Explain what state web2 is left in after that run and after a second run that finishes without errors. How would you detect it and how would you fix it without force_handlers?

Solutions

Exercise 1. First run: all three tasks return changed (the two copies create the files and command always reports a change), so First and Second are notified. Each runs once and in definition order:

RUNNING HANDLER [First] ****
RUNNING HANDLER [Second] ****

Second run: the copies return ok, but command still returns changed and notifies First. Only RUNNING HANDLER [First] appears. This is the mistake from the "Common Mistakes" section: the query should have changed_when: false, and then it would never notify.

Exercise 2.

  tasks:
    - name: File one
      ansible.builtin.copy:
        dest: /tmp/one.txt
        content: "1\n"
      notify: Files changed
    - name: File two
      ansible.builtin.copy:
        dest: /tmp/two.txt
        content: "2\n"
      notify: Files changed
  handlers:
    - name: First
      ansible.builtin.debug:
        msg: First
      listen: Files changed
    - name: Second
      ansible.builtin.debug:
        msg: Second
      listen: Files changed

The order doesn't change: it's still the definition order (First, Second), and each one runs once even though the topic is notified twice. Delete /tmp/one.txt and /tmp/two.txt from web1 when you're done.

Exercise 3. After the first run, the new gzip.conf is on disk but nginx keeps the previous configuration (the handler was discarded when the host failed). On the second run the gzip.conf task returns ok, doesn't notify, and the reload never comes: the drift between disk and memory persists even though the PLAY RECAP says failed=0. You detect it by checking the actual behavior (for example, the compression headers with curl -sI -H 'Accept-Encoding: gzip' http://192.168.56.12/robots.txt) or the service's reload time. You fix it by reloading by hand, for example with ansible web2 -b -m ansible.builtin.systemd_service -a "name=nginx state=reloaded", or by rerunning the playbook with --force-handlers on the run that failed (afterwards, nothing is notified anymore). That's why Aurora sets force_handlers = True in ansible.cfg.

Conclusion

You've replaced Aurora's three temporary tasks with handlers. You know that a handler is a task that only runs when another task notifies it with a changed result, that it runs once per host at the end of each section of the play (after pre_tasks, after roles/tasks and after post_tasks) and in its definition order, that in roles it lives in handlers/main.yml, and that listen lets several actions respond to the same topic. With that, the nginx role validates the configuration with nginx -t before reloading (Validate the nginx configuration and Apply the nginx reload, both listening to Reload nginx), and the postgresql role has Restart PostgreSQL and Reload PostgreSQL, with a meta: flush_handlers that applies the restart before creating users and databases on the right port. You also know the trap of handlers discarded after a failure, and you've closed it with force_handlers = True. But the nginx and PostgreSQL configuration is still written inside the tasks with copy and content:, mixing YAML with each service's syntax. In the next lesson, Jinja2 Templates, you'll move it into template files in the roles' templates/ directories, with conditionals, loops and validation, and you'll take the opportunity to manage the complete nginx.conf and pg_hba.conf as well.

© Copyright 2026. All rights reserved