Ansible Handlers and Notification Behaviour
A handler is a task that runs only if something notified it, only once however many times it was notified, and only at the end of the play. Those three rules make it exactly right for restarting a service after a configuration change - and the fourth rule, that a later failure cancels it, is the one that bites.
Plays and Playbooks Guide 15 of 45 Intermediate
- OSUbuntu 26.04 LTS
- ansible-core2.20.1
- Python3.14.4
- TimeAbout 15 min
Handlers are notified by task name, so renaming a task's handler breaks the link silently - the notify simply matches nothing. listen: gives a handler an additional topic name and lets several handlers respond to one notification, which is more robust for anything shared.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| ANS-CTL01 | 192.168.0.36 | Ubuntu 26.04 LTS | Ansible Control Node | 2 Core | 3 GB | 50 GB |
| ANS-A01 | 192.168.0.37 | Ubuntu 26.04 LTS | Managed Node (group: web) | 2 Core | 3 GB | 50 GB |
This guide includes
Use this when a service should restart only if something actually changed. This matters because a handler runs once at the end and only if notified - and a later failure cancels it silently.
- notifying one handler from two tasks, and watching it run once at the end
- running again with nothing changed, so nothing is notified at all
- watching a handler be skipped because a later task failed
- fixing that with one line -
force_handlers
Before you start
- A control node configured as shown in the first step.
- The session writes several
/etc/motd.d-demo-*files on thewebhost and removes them at the end.
-
The configuration this guide assumes
-
A handler runs once, at the end
-
Nothing changed, so nothing is notified
-
A handler that is skipped because of a failure
-
force_handlers fixes it