Junior
What are handlers?
sobes.tech AI
Answer from AI
Handlers in the context of DevOps, especially in tools like Ansible, are tasks or blocks of code that execute only under certain conditions — when they are explicitly "notified" by another task. They are used to restart services, reboot servers, or perform other actions that should only occur after significant configuration changes.
Key features:
- Executed upon notification: A handler runs only after one or more tasks explicitly "notify" it (for example, using
notifyin Ansible). - Run once: Even if multiple tasks notify the same handler, it will only execute once at the end of the playbook or within the
include_tasks/import_taskssection where it is defined. This prevents multiple restarts of services. - Declarative approach: They allow you to declaratively specify what actions should be taken when the system's state changes, without worrying about manually triggering these actions.
Example of notifying a handler in an Ansible task:
- name: Configure web server # Task that may change configuration
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: # Notify the handler
- restart nginx
Definition of a handler:
handlers:
- name: restart nginx # Handler name, matches the name in notify
service:
name: nginx
state: restarted