automationansibletaskhandler

In Ansible, how do I run a task when ANY change is detected?


I have some Raspberry Pis running Alpine Linux in diskless mode. This requires certain changes to be committed via lbu. I have the following handler:

- name: Commit changed files on Alpine Linux
  when: ansible_os_family == "Alpine"
  community.general.lbu:
    commit: true

And it's easy enough to use

- name: Task
  ...
  notify:
    - Commit changed files on Alpine Linux

It seems like it'll become repetitive (and potentially error prone) needing to notify on every task. Is there a way to execute a task and/or handler if ANY change happens anywhere in a playbook?


Solution

  • I'm afraid it's not possible without grouping the tasks that potentially change the system state in a block as suggested by Zeitunator in the comments.

    Moreover, handlers work not exactly as you expect - they could be notified by any number of tasks but they only run once after the play is finished by default.

    From Controlling when handlers run:

    By default, handlers run after all the tasks in a particular play have been completed. Notified handlers are executed automatically after each of the following sections, in the following order: pre_tasks, roles/tasks and post_tasks. This approach is efficient, because the handler only runs once, regardless of how many tasks notify it. For example, if multiple tasks update a configuration file and notify a handler to restart Apache, Ansible only bounces Apache once to avoid unnecessary restarts.

    To achieve what you want, you will have not only to notify them, but also to add meta: flush_handlers after each task.