Plays that use roles are not limited to just roles. These plays can have tasks of their own, as well as two other blocks of tasks: pre_tasks and post_tasks. The order in which these are executed is not dependent upon which order these sections are listed in the play itself; instead, there is a strict order to block execution within a play. See Chapter 1, The System Architecture and Design of Ansible, for details on the playbook order of operations.
Handlers for a play are flushed at multiple points. If there is a pre_tasks block, handlers are flushed after all pre_tasks are executed. Then, the roles and tasks blocks are executed (roles first, then tasks, regardless of the order they are written in the playbook), after which handlers will be flushed again. Finally, if a post_tasks block exists, handlers will be flushed once again after all post_tasks have executed. Of course, handlers can be flushed at any time with the meta: flush_handlers call. Let's expand on our roleplay.yaml to demonstrate all the different times handlers can be triggered:
---
- hosts: localhost
gather_facts: false
pre_tasks:
- name: pretask
debug:
msg: "a pre task"
changed_when: true
notify: say hi
roles:
- role: simple
derp: newval
tasks:
- name: task
debug:
msg: "a task"
changed_when: true
notify: say hi
post_tasks:
- name: posttask
debug:
msg: "a post task"
changed_when: true
notify: say hi
handlers:
- name: say hi
debug:
msg: "hi"
We'll also modify our simple role's tasks to notify the say hi handler as well:
--- - name: print a variable debug: var: derp changed_when: true notify: say hi
Running our playbook should result in the say hi handler being called a total of three times: once for pre_tasks, once for roles and tasks, and once for post_tasks:
While the order in which pre_tasks, roles, tasks, and post_tasks are written into a play does not impact the order in which those sections are executed, it's best practice to write them in the order that they will be executed. This is a visual cue to help remember the order and to avoid confusion when reading the playbook later.