Sometimes you want to run a task, with the condition that another task makes changes to the managed node. For example, you might want to save the configuration or retrieve a backup from a network device only when a configuration changes in network device. more practical examples are when managed nodes are servers. For example, you might want to restart a service like Apache only when the configuration of the service changes. If there are no changes in the Apache configuration file, you do not want to restart the service which disrupt the service. The solution in Ansible Handler, which is the topic of this video.
Handlers are normal tasks, but they run only when they are “notified” by another normal task and only when it changes something in managed node. Each handler task “listens” to a globally unique name. This is the name which must be notified by another normal task that will trigger the execution of the handler task.
root@debian:~/ansible-project1# cat handler.yaml
---
- hosts: csr1
gather_facts: false
connection: network_cli
tasks:
- name: change config
ios_config:
lines: hostname {{ inventory_hostname }}
notify: config_changed
register: response
handlers:
- name: "changes.."
listen: config_changed
debug:
msg: "{{ response }}"
access ansible codes of this course in github
this is a video-based training therefore the output of running commands are not show in the text.
To add two pints to the discussion: first, if handler task is notified multiple times in a play, it will be run only once, and second point, it will run by default after all tasks in a given play have been completed. For example, if you say that a service needs to be restarted if config file1 or config file2 is changed. If both configuration files are changed, the service will restart only once and after both configuration files have been changed.
ansible handler in asnible website
In our playbook, we change the hostname of the router and if the hostname is changed then it will notify “config_changed” handler which displays the result of changes otherwise handler is not notified and nothing will be displayed.