Determine the Order of the Handlers#
Problem#
We have 2 tasks in which we potentially notify Handlers. How to determine or change the order of Handlers?
tasks/main.yml
- name: Configure Nginx service
ansible.builtin.template:
src: nginx.service.j2
dest: /etc/systemd/system/nginx.service
owner: root
group: root
mode: "0644"
notify: Nginx restart
- name: Add managed vhost config files.
ansible.builtin.template:
src: "{{ item.template | default(nginx_vhost_template) }}"
dest: "{{ nginx_vhost_path }}/{{ item.filename }}"
owner: root
group: www-data
mode: 0644
with_items: "{{ nginx_vhosts }}"
notify: Nginx reload
Solution#
The order of execution of Handlers is based how they are ordered in your YAML configuration.
handlers/main.yml
# Executed first
- name: Nginx reload
ansible.builtin.systemd:
name: nginx
state: reloaded
# Executed second
- name: Nginx restart
ansible.builtin.systemd:
name: nginx
state: restart
Explanation#
Handler are not executed according to the order of notify, but, as with tasks, according to the declared order. In our solution, we have therefore deliberately set reload before restart.
Flush Handlers per Role
Orders of Handlers are defined per Play, so the order of your Roles in your Playbook and their Handlers define the order of execution of the Handlers. However, it often makes sense to have a Task at the end of each Role for flushing the Handlers related to coresponding Role.
- name: Flush handlers now
ansible.builtin.meta: flush_handlers