Use of Handlers in Ansible

In this Blog, we are going to discuss about one of the best feature of Ansible named Handlers. Above 90% module of the ansible follow the rule of idempotency. Idempotency is a functionality of Ansible by which it first check the presence of the task which it is going to do.
Lets suppose we want to install httpd software in target node by using Ansible. So during installation , it first check in target node whether the httpd software is present or not. If it exist already, the playbook show this in green color and if it does not exist, then it will perform it’s action. But there is some other modules and keywords like ‘restarted’ which doesn’t follow the idempotence rule. These modules will perform their action every time. It consume our resources and consume time also.
There is an alternative also to get rid of this situation, we can use Handlers.
What are Handlers ?
Sometimes you want a task to run only when a change is made on a machine. 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.
# e.g of handlers in playbook
handlers:
— name: service start
service:
name: httpd
state: restarted
Here you can see that the name of the handler is ‘service start’. We have to notify this handler on change.
notify:
— service start
I am using the handlers in configuration of webserver and on changing of the conf file, port number it will notify the handlers and then handlers will restart the httpd service.
Complete code of the playbook :
# cat var.yml
- changeport: 8132
- pagedir: /var/www/arth
---------------------------------------
New configuration file which is copied to target node is :# cat lalit.confListen {{ changeport }}<Virtualhost {{ ansible_default_ipv4.address }}:{{ changeport }}>
DocumentRoot {{ pagedir }}</Virtualhost>
On running the playbook, it will also run the handlers. Here I have used 8134 port no. and it worked good.

1st time running handlers also.
Again if we play the same playbook without any Changement, it will not notify the handlers.

No handlers will be notified.

Again handlers are notified.
In the last , I used 8132 port no. and again it notifies the handlers and these will restart the service.

Thank you.