Junior — Middle
Could you explain what Ansible handlers are and how they function in configuration automation?
sobes.tech AI
Answer from AI
Ansibles handlers are special tasks that are only executed when they are referenced by other tasks via the notify directive.
They are useful for performing actions that should only occur when a state changes, such as restarting a service after updating a configuration file.
How it works:
- In a playbook or role, a task makes some change (e.g., configuration).
- If the task actually made changes, it calls
notifywith the handler's name. - At the end of the playbook execution, all called handlers are run once.
Example:
- name: Update configuration file
template:
src: config.j2
dest: /etc/myapp/config.conf
notify: Restart myapp
handlers:
- name: Restart myapp
service:
name: myapp
state: restarted
In this example, the myapp service will restart only if the configuration was changed.