Ansible Handlers Notified in a Failed Run Never Fire, and the Re-run Sees Nothing to Change
An Ansible handler runs only if a task notified it during the same run, and only when the play reaches the point where handlers are flushed. If the play fails after a configuration task changed a file but before its handlers ran, the restart is lost. The next run finds the file already correct, reports ok, notifies nothing, and the service keeps running its old configuration while the playbook reports success.
How Handlers Are Queued
A task that reports changed adds its notify targets to a queue. By default the queue is flushed after all the tasks of a play section, and each notified handler runs once:
tasks:
- name: Update configuration file
ansible.builtin.template:
src: config.j2
dest: /etc/myapp/config.conf
notify: Restart MyApp
handlers:
- name: Restart MyApp
ansible.builtin.systemd:
name: myapp
state: restarted
The queue lives only in the running ansible-playbook process. Nothing on the target remembers that a restart is pending.
The Lost Notification
- Run 1: the template task writes the new file (
changed) and queues the restart. - A later task fails, for example on a missing sudo password or a network timeout. The play stops on that host, and its queued handlers are dropped.
- Run 2, after the fix: the template task compares the file, finds it identical, reports
ok, and queues nothing. - The play ends green. The file on disk is new, the process in memory is old.
Making Restarts Survive Failures
--force-handlerson the command line, orforce_handlers: trueon the play, runs the handlers already notified on a host even when a later task fails there.ansible.builtin.meta: flush_handlersright after the change restarts the service before the riskier tasks that follow.- After the fact, restart the service with an ad hoc command, since no playbook run will do it any more:
ansible webservers -m systemd -a "name=myapp state=restarted" -b -K
Whether a task counts as changed decides everything here; for command and shell tasks that is up to you (see Ansible Reports Every command and shell Task as Changed Unless creates or changed_when Decides).
References
- DevOps and Infrastructure as Code MOC - hub for automation notes.
- Ansible Reports Every command and shell Task as Changed Unless creates or changed_when Decides - the change status that triggers or silences a handler.
- kubelet Depends on containerd Through the CRI Socket - why containerd needs a restart to read its configuration.
- Ansible documentation: Handlers - notification, flushing and
meta: flush_handlers. - Ansible documentation: Error handling in playbooks - handlers and failure,
force_handlers.