Sobes.tech
Junior — Middle

Is it possible to insert a handler in the middle of a Playbook sequence?

sobes.tech AI

Answer from AI

In an Ansible Playbook, you cannot directly "insert" a handler into the middle of a task sequence. Handlers are defined separately and are called automatically when a task with notify reports a change.

However, if you need to perform certain actions in the middle of a playbook, you can:

  • Call a separate task that performs the required actions.
  • Use meta: flush_handlers to immediately run all accumulated handlers at the desired moment.

Example of using meta: flush_handlers:

- name: Execute tasks
  tasks:
    - name: Change configuration
      template:
        src: config.j2
        dest: /etc/myapp/config
      notify: Restart service

    - meta: flush_handlers  # Immediately runs handlers

    - name: Continue executing tasks
      command: echo "Further actions"

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

Thus, handlers are not inserted in the middle, but you can control when they are executed.