Ansible: Automate Everything from First Playbook to Production · Playbooks: Tasks, Handlers and Conditionals

Handlers: Restart Services Only When Config Changes

Use handlers and notify so Nginx restarts only when its configuration file actually changes — not on every playbook run.

Members can save this page, take notes and track progress. See membership · Sign in

What you'll build

A playbook that deploys an Nginx virtual-host config and restarts the service only when the config file changed. If you run the playbook and nothing changed, the handler never fires and Nginx keeps serving without interruption.

The idea

A handler is a task that runs only when notified. A regular task can include notify: <handler name> — if that task reports changed, the handler is queued. Handlers run once at the end of the play (after all tasks), no matter how many tasks notified them.

tasks:
  - name: Deploy nginx config
    ansible.builtin.template:
      src: nginx.conf.j2
      dest: /etc/nginx/sites-available/default
    notify: Restart nginx        # handler fires only if this task changed the file

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

This pattern avoids unnecessary service restarts:

  • First run: config is new → task reports changed → handler restarts Nginx.
  • Second run: config is identical → task reports ok → handler does not fire.

If you need a handler to fire immediately (not at the end of the play), use ansible.builtin.meta: flush_handlers as a task.

listen lets multiple handlers share a trigger name:

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

  - name: Clear nginx cache
    ansible.builtin.file:
      path: /var/cache/nginx
      state: absent
    listen: web config changed

Now any task that uses notify: web config changed triggers both handlers.

The code

Deploy config with a handler that restarts on change
mkdir -p ansible-lab && cd ansible-lab

cat > ansible.cfg << 'EOF'
[defaults]
inventory = inventory.ini
host_key_checking = False
stdout_callback = yaml
EOF

cat > inventory.ini << 'EOF'
[webservers]
localhost ansible_connection=local
EOF

mkdir -p templates

cat > templates/default.conf << 'EOF'
server {
    listen 80 default_server;
    server_name _;
    root /var/www/html;

    location / {
        try_files $uri $uri/ =404;
    }

    # Enable gzip
    gzip on;
    gzip_types text/plain text/css application/json;
}
EOF

cat > deploy-nginx.yml << 'EOF'
---
- name: Deploy Nginx with handler
  hosts: webservers
  become: true

  tasks:
    - name: Install nginx
      ansible.builtin.apt:
        name: nginx
        state: present
        update_cache: true
        cache_valid_time: 3600

    - name: Deploy virtual host config
      ansible.builtin.copy:
        src: templates/default.conf
        dest: /etc/nginx/sites-available/default
        owner: root
        group: root
        mode: "0644"
      notify: Restart nginx

    - name: Ensure nginx is enabled
      ansible.builtin.service:
        name: nginx
        enabled: true

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

echo "=== First run (config deployed) ==="
ansible-playbook deploy-nginx.yml 2>&1 | grep -E "TASK|changed|ok|RUNNING HANDLER|PLAY RECAP" | head -20
echo ""
echo "=== Second run (nothing changed) ==="
ansible-playbook deploy-nginx.yml 2>&1 | grep -E "TASK|changed|ok|RUNNING HANDLER|PLAY RECAP" | head -20

Output

=== First run (config deployed) ===
/tmp/tmp9_jl7l8y/script.sh: line 69: ansible-playbook: command not found

=== Second run (nothing changed) ===
/tmp/tmp9_jl7l8y/script.sh: line 72: ansible-playbook: command not found

Run this on your computer — see “Get Started” for setup.

First run: the config file was new, so the copy task reported changed and the handler restarted Nginx. Second run: the file was already in place, the task reported ok, and the handler never ran — ok=4 instead of ok=5.

Common mistakes

  • Putting the restart in a regular task instead of a handler. A regular service: state=restarted task runs on every playbook execution, bouncing the service even when nothing changed. Handlers fire only on actual changes.
  • Misspelling the handler name. notify: Restart Nginx does not match a handler named Restart nginx (case-sensitive). Ansible silently ignores the notification and the service is never restarted. Use listen: with a simple label to reduce typo risk.
  • Assuming handlers run between tasks. Handlers run at the end of the play by default. If a later task depends on the restarted service, add - ansible.builtin.meta: flush_handlers before that task to force immediate execution.
  • Multiple tasks notifying the same handler. The handler still runs only once — Ansible deduplicates notifications. This is correct behaviour, but can surprise you if you expect two restarts.

Key points

  • Handlers are tasks that run only when notified by a changed task.
  • They execute once at the end of the play, regardless of how many tasks notify them.
  • Use listen: to trigger multiple handlers from one notification label.
  • Use meta: flush_handlers to force handlers to run mid-play when a later task depends on the restart.
  • Never use a regular task for service restarts — always use a handler so the restart is conditional.

Further reading: Handlers · meta module

Practice questions

When do handlers run relative to regular tasks?

Answer

Handlers run once at the end of the play, after all regular tasks have completed. If you need a handler to fire before a later task, insert a 'meta: flush_handlers' task at the point where the handler must have run.

What happens if two different tasks notify the same handler?

Answer

The handler runs only once. Ansible deduplicates handler notifications — no matter how many tasks trigger the same handler in a single play, it executes a single time at the end of the play.

Why is 'listen' useful for handlers?

Answer

listen lets multiple handlers subscribe to the same event name. A task that notifies 'web config changed' can trigger both a service restart and a cache clear, without the task needing to know about each handler individually. It also reduces the risk of name typos.

Open in the app to mark lessons complete, take notes and track your progress.

Last reviewed · By the ByteCamel team · How we write content

Was this page helpful?

Report a mistake