Loading

Quipoin Menu

Learn • Practice • Grow

ansible / Ansible Handlers
tutorial

Ansible Handlers

Sometimes you want a task to run only when another task makes a change – for example, restart a service only if a configuration file was updated. Handlers are special tasks that run once at the end of a play, but only if notified.

What Are Handlers?

Handlers are like regular tasks, but they are only triggered by the notify directive from another task. They run after all other tasks in the play complete, and only once even if notified multiple times.

Handlers are ideal for service restarts or other actions that should happen only when something changes.

Example: Restart Nginx After Config Change

---
- name: Update nginx config and restart
hosts: webservers
become: yes
tasks:
- name: Copy new config file
copy:
src: nginx.conf
dest: /etc/nginx/nginx.conf
notify: restart nginx

handlers:
- name: restart nginx
service:
name: nginx
state: restarted
If the copy task changes the file (i.e., it was not already identical), it notifies the handler. The handler runs at the end of the play.

Multiple Notifications

You can notify multiple handlers from one task, or notify the same handler from multiple tasks. Each handler runs only once.

Handler Names Are Important

The notify value must match the handler’s name exactly. Keep names unique and descriptive.

Listening for Handlers

You can also use listen to group handlers. Multiple handlers can listen to the same topic.
handlers:
- name: restart nginx
listen: "restart web services"
service:
name: nginx
state: restarted
- name: restart php-fpm
listen: "restart web services"
service:
name: php-fpm
state: restarted
Then notify with notify: "restart web services" to trigger both.


Two Minute Drill
  • Handlers run only when notified by a task that made a change.
  • Define handlers in the handlers section of a play.
  • Use notify: handler_name in a task.
  • Handlers run once at the end of the play, after all tasks.

Need more clarification?

Drop us an email at career@quipoinfotech.com