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: copy my webpage
- name: copy conf file
- name: Start Apache Service
- name: restart_service
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…
Feel free to connect on linkedin…😊
Having any issues related to the article, please DM me…