What is the purpose of the 'handlers' directory in an Ansible Role?

QuestionsQuestions8 SkillsProAnsible RolesAug, 21 2025
0241

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:

  1. Define a handler in handlers/main.yml:

    ---
    - name: Restart my service
      service:
        name: my_service
        state: restarted
  2. 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.

0 Comments

no data
Be the first to share your comment!