What are handlers?
Handlers are special tasks that run only when notified by a task that reported changed. Typical uses: restart Nginx, reload Apache, bounce an app.
Without handlers, you might restart Nginx on every playbook run — bad for production.
With handlers:
Task changes something
↓
notify
↓
Handler runs (once per play, by default at end)
Example
---
- name: Handler demo
hosts: all
become: true
tasks:
- name: Copy nginx config
copy:
src: nginx.conf
dest: /etc/nginx/nginx.conf
notify:
- Restart nginx
handlers:
- name: Restart nginx
service:
name: nginx
state: restarted| Keyword | Purpose |
|---|---|
notify | Queue a handler |
handlers | Handler definitions |
Handler name | Must match the notify string exactly |
Handler runs only if the notifying task status is changed.
Multiple notifications
notify:
- Restart nginx
- Reload firewallMultiple notifies to the same handler in one play collapse into a single handler run.
Mini project — deploy site + restart on change
---
- name: Deploy website
hosts: all
become: true
tasks:
- name: Deploy index file
template:
src: index.html.j2
dest: /var/www/html/index.html
notify:
- Restart nginx
handlers:
- name: Restart nginx
service:
name: nginx
state: restartedFlush handlers mid-play if you need the restart before later tasks:
- meta: flush_handlersPrefer state: reloaded for Nginx config changes when a full restart is unnecessary.