The handlers directory in an Ansible Role is used to define handlers, which are special tasks that are triggered by notifications from other tasks. Handlers are typically used for actions that should only be executed when a change occurs, such as restarting a service after a configuration file has been modified.
Handlers are defined in a separate file within the handlers directory, and they are called using the notify directive in a task. When a task notifies a handler, the handler will run at the end of the playbook execution if the task resulted in a change.
Here’s a simple example of how to use a handler:
-
Define a handler in
handlers/main.yml:--- - name: Restart my service service: name: my_service state: restarted -
Notify the handler in a task in
tasks/main.yml:--- - name: Update configuration file copy: src: my_config.conf dest: /etc/my_service/my_config.conf notify: Restart my service
In this example, if the configuration file is changed, the handler to restart my_service will be triggered.
