Ansible Handlers Notified in a Failed Run Never Fire, and the Re-run Sees Nothing to Change

In progress Ansible

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

  1. Run 1: the template task writes the new file (changed) and queues the restart.
  2. 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.
  3. Run 2, after the fix: the template task compares the file, finds it identical, reports ok, and queues nothing.
  4. The play ends green. The file on disk is new, the process in memory is old.

Making Restarts Survive Failures

  • --force-handlers on the command line, or force_handlers: true on the play, runs the handlers already notified on a host even when a later task fails there.
  • ansible.builtin.meta: flush_handlers right 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