Working with Handlers in Ansible

Gaurav Gupta
2 min readJun 12, 2021

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
tasks:
- name: Install Apache Server
dnf:
name: "httpd"
state: present
- name: copy my webpage
template:
src: "index.html"
dest: "/var/www/html"
- name: copy conf file
copy:
src: handlers/apache.conf
dest: /etc/httpd/conf.d
notify: restart_service
- name: Start Apache Service
service:
name: httpd
state: started
handlers:
- name: restart_service
service:
name: httpd
state: restarted

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

LISTEN 8080

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…

--

--