Sobes.tech
Junior — Middle

Explain the mechanism of interaction and task handling in Ansible.

sobes.tech AI

Answer from AI

In Ansible, handlers are special tasks that are executed only when notified (notify) by other tasks. The mechanism works as follows:

  • You define handlers with unique names in your playbook or role.
  • Regular tasks can include a notify directive pointing to a handler's name.
  • If a task changes the state (for example, updates a configuration), it "notifies" the handler.
  • All notifications are collected, and handlers are executed once at the end of the current playbook or role.

This prevents repeated execution of the same actions and ensures handlers are run only when necessary.

Example:

- name: Update configuration file
  copy:
    src: config.cfg
    dest: /etc/myapp/config.cfg
  notify: Restart service

handlers:
  - name: Restart service
    service:
      name: myapp
      state: restarted