In my previous blogs we can see how Ansible is used for automation of tasks and how it aims to provide improvements in productivity to a wide variety of automation challenges,
But when it comes to the case where you want a task to run only when a change is made on a machine. Like you may want to restart a service only if updates have been made to the configuration of that service, not if the configuration is unchanged. For example, restarting HTTPD Service is not idempotence in nature and also consume more resources.
The answer to such cases is Ansible Handlers. Ansible Handlers are tasks that only run when notified and Each handler should have a globally unique name.
So here we have an Ansible playbook (YAML) code here without using handler:
- hosts: all
tasks:
- copy:
src: "/root/Ansible/home.html"
dest: "/var/www/html/"
- service:
name: "httpd"
state: restarted
enabled: yes
- firewalld:
port: 80/tcp
permanent: yes
state: enabled
immediate: yes
When we run this code for the first-time HTTPD service will be restart on managed node which we don't want without any change in the configuration. So, to resolve this issue we use Ansible Handler which are the tasks that only run when configuration is changed.
- hosts: all
tasks:
- copy:
src: "/root/Ansible/home.html"
dest: "/var/www/html/"
notify:
- Restart Httpd
- firewalld:
port: 80/tcp
permanent: yes
state: enabled
immediate: yes
handlers:
- name: Restart Httpd
service:
name: "httpd"
state: restarted
enabled: yes
Here, with the handlers in Ansible-Playbook, the code will restart service only if there is some changes in the configuration file.