Working with Handlers in Ansible

If you are familiar with using Ansible, you might have come across certain situations where you won’t be able to get the benefit of the Idempotence nature of Ansible.

For example, you may want to restart a service if a task updates the configuration of that service, but not if the configuration is unchanged.

Ansible uses handlers to address this use case. Handlers are tasks that only run when notified. Each handler should have a globally unique name.

We provide a notify keyword to a task, which triggers handler. This handler only runs when any changes in task happen.

Let’s understand this with one example…

We write a playbook to launch apache webserver, first time it runs normally. Now I need to change the port number in the conf file of httpd software. But this time, when I run the playbook again it doesn’t start the service again. Here we need to restart the service. But if I write this, whenever I run the playbook, it always runs this task. So this created some overhead. To solve this issue, we normally use handlers in the playbook.

- hosts: web
- name: Install Apache Server
name: "httpd"
state: present
- name: copy my webpage
src: "index.html"
dest: "/var/www/html"
- name: copy conf file
src: handlers/apache.conf
dest: /etc/httpd/conf.d
notify: restart_service
- name: Start Apache Service
name: httpd
state: started
- name: restart_service
name: httpd
state: restarted

Now let me change port number in handlers/apache.conf file…


Now if I run the playbook again, it doesn’t run the handler until I do change in conf file.

In this way, we can achieve idempotence in the Ansible playbook.

Hope you enjoyed it…

Thankyou :)

Feel free to connect on linkedin…😊

Having any issues related to the article, please DM me…



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store