Home DevOpsAnsible Handlers Explained: Automate Service Restarts

Ansible Handlers Explained: Automate Service Restarts

by Knowledge Base Linux
Ansible handlers automating service restarts across Linux servers

Ansible handlers are the mechanism that stops your playbooks from restarting services on every run, and understanding them is the step that turns a working playbook into an idempotent one. A handler is a task that runs only when it is notified by another task that actually changed something, and all notified handlers run once at the end of the play, in the order they are defined. That design solves a real operational problem: restarting nginx on every playbook run drops connections and creates noise for no benefit, while restarting it only when its configuration changed is both safer and faster. This guide explains handlers, the notify keyword, the listen feature, flushing, and the mistakes that make handlers appear to do nothing.

The mental model to keep is simple: normal tasks run in order and report changed or ok, while handlers wait quietly until the end of the play and then run once for each notification, no matter how many tasks notified them. If three tasks all change files that notify the same restart handler, the service still restarts once, not three times. That deduplication is the whole point, and it is why handlers belong to a play rather than to a single task. If you are new to Ansible structure, our Ansible roles guide shows where handlers live inside a role, alongside tasks, templates, and defaults.

Ansible handlers chain from config change to service restart

Prerequisites

You need Ansible installed on a control node, at least one managed Linux host reachable over SSH, and a basic playbook you can run repeatedly. The examples use nginx on Ubuntu, but the pattern is identical for Apache, PostgreSQL, systemd units, and any service with a configuration file. You should be comfortable running ansible-playbook with an inventory file and reading its changed and ok output, because the handler behaviour is visible only in that output: a handler that runs appears at the end of the play under RUNNING HANDLER, while a handler that was not notified does not appear at all. No Galaxy collections are required for the core examples.

Ansible Handlers: Your First Notify and Restart

Consider a playbook that installs nginx and deploys a configuration template. Without a handler, you would restart the service unconditionally, which is wasteful and disruptive. With a handler, the template task notifies a restart handler only when the rendered file differs from the file already on the host. On the first run the file changes and the service restarts; on the second run nothing changes, nothing is notified, and the service is left alone, which is exactly the idempotence Ansible promises.

- hosts: webservers
  become: true
  tasks:
    - name: Install nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true

    - name: Deploy nginx configuration
      ansible.builtin.template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
        mode: "0644"
      notify: Restart nginx

  handlers:
    - name: Restart nginx
      ansible.builtin.service:
        name: nginx
        state: restarted

Run the playbook twice and compare the output. The first run should show the template task as changed and a RUNNING HANDLER section at the end; the second run should show everything as ok and no handler section. That second run is the proof that the handler works: a playbook that restarts services on an ok run is not idempotent, no matter how clean it looks. The official Ansible documentation on handlers in playbooks describes this notify and run-once behaviour as the canonical pattern.

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

Ansible Handlers: Listen, Multiple Handlers, and Ordering

As playbooks grow, several tasks may need to trigger the same action under different names, and that is what listen is for. A handler with a listen topic can be notified by that topic name from any task, which decouples the task from the handler name and lets one handler serve many callers. This is especially useful in roles, where a task in one role can notify a shared topic without knowing the handler’s exact name. A handler can also listen on multiple topics, and a task can notify multiple handlers by listing them.

  tasks:
    - name: Deploy nginx configuration
      ansible.builtin.template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: Restart web services

    - name: Deploy site configuration
      ansible.builtin.template:
        src: site.conf.j2
        dest: /etc/nginx/sites-available/site.conf
      notify: Restart web services

  handlers:
    - name: Restart nginx
      ansible.builtin.service:
        name: nginx
        state: restarted
      listen: Restart web services

Handler order is another detail that surprises people: handlers run in the order they are defined in the handlers section, not in the order they were notified. If you need a configuration validation handler to run before a restart handler, define validation first, regardless of which task notified which. And if a handler itself notifies another handler, that second handler runs after the current handler queue, which is a legitimate way to chain actions such as validating a configuration and then reloading the service only if validation passed. For service management fundamentals, see our guide to managing services with systemd on Ubuntu, which explains the restart, reload, and enable states handlers typically invoke.

Ansible Handlers: Flush, Force, and When Handlers Do Not Run

By default, handlers run at the end of the play, which means a later task in the same play still sees the old service state. When order matters, flush_handlers forces all notified handlers to run immediately at that point in the play. The classic case is a task that deploys a configuration, a flush, and then a task that tests the service over HTTP: without the flush, the test would hit the old configuration and fail intermittently. Use flush_handlers sparingly, because overusing it defeats the deduplication benefit, but use it deliberately wherever a later task depends on the restarted state.

  tasks:
    - name: Deploy nginx configuration
      ansible.builtin.template:
        src: nginx.conf.j2
        dest: /etc/nginx/nginx.conf
      notify: Restart nginx

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

    - name: Verify nginx responds
      ansible.builtin.uri:
        url: http://localhost/
        status_code: 200

There is one more behaviour you must know: if a play fails, handlers that were notified but had not yet run are not executed by default, because Ansible stops the play on failure. That is usually what you want, since a half-applied play should not restart a service into an inconsistent state, but it can surprise you when a failed later task leaves a service unrestarted. The –force-handlers command-line flag runs notified handlers even when the play fails, which is useful for cleanup scenarios but should be used consciously, not as a default. You can also set force_handlers at the play level for plays where restarting into the new configuration is safer than leaving the old one running.

Troubleshooting

When a handler does not run, check the task output first: handlers only fire on changed, never on ok, so a task that reports ok correctly produces no notification. If the task should have changed but reports ok, the usual cause is a template or copy task whose source and destination already match, which means the handler is working and your expectation is wrong. If the task reports changed but no handler runs, check the spelling of the notify name against the handler name or listen topic, because a mismatched name fails silently in older Ansible versions and produces a warning in newer ones. Also check that the handler is defined in the same play: handlers are scoped to a play, so a handler defined in one play cannot be notified from another, and roles define their handlers in handlers/main.yml for exactly this reason.

When a handler runs but the service does not actually restart, check whether the handler used state restarted or reloaded: reload is gentler but only works if the service supports it and only picks up certain configuration changes, while restart always applies the new configuration at the cost of a brief outage. If a handler restarts the service too often, look for a task that changes on every run, such as a template with a timestamp or a command task without creates or changed_when, because that task notifies the handler on every run and defeats the design. Fix the task’s idempotence, not the handler, and the restarts will stop.

Conclusion

Ansible handlers are a small feature with an outsized effect on operational safety: they make restarts a consequence of real change, they deduplicate repeated notifications into a single restart, and they give you flush and listen tools for the cases where order and sharing matter. Define handlers in the play or role that owns the service, notify them only from tasks that genuinely change configuration, verify idempotence by running the playbook twice, and use flush_handlers where a later task depends on the new state. Once that habit is in place, your playbooks stop interrupting services for no reason, and every restart in your logs means something actually changed.

You may also like

KbLinux

Typically replies within a day

Hello, Welcome to the site. Please click below button for chatting me through Telegram.