Ansible - Handlers
- Handlers are tasks that are launched when they are notified by another task and that task has made a change.
 - Handlers are run in the order that they are defined.
 - They are run once even if notified multiple times.
 - They only run when notified.
 - Use unique names otherwise only one will be notified.
 - Handlers are all in one scope even when using roles.
 - Handlers are run after these sections: pre_tasks, roles/tasks and post_tasks
 - They can be flushed early and then re-notified again.
 
Using a handler:
  - name: write the apache config file
    template:
      src: /srv/httpd.j2
      dest: /etc/httpd.conf
    notify:
    - restart apache
  - name: ensure apache is running
    service:
      name: httpd
      state: started
  handlers:
    - name: restart apache
      service:
        name: httpd
        state: restarted
Notify multiple handlers:
- name: template configuration file
  template:
    src: template.j2
    dest: /etc/foo.conf
  notify:
     - restart memcached
     - restart apache
handlers:
    - name: restart memcached
      service:
        name: memcached
        state: restarted
    - name: restart apache
      service:
        name: apache
        state: restarted
Using a var ( won’t change if the var changes mid play):
handlers:
# this handler name may cause your play to fail!
- name: restart "{{ web_service_name }}"
Handlers listening to a topic ( decouple handlers from names ):
handlers:
    - name: restart memcached
      service:
        name: memcached
        state: restarted
      listen: "restart web services"
    - name: restart apache
      service:
        name: apache
        state: restarted
      listen: "restart web services"
tasks:
    - name: restart everything
      command: echo "this task will restart the web services"
      notify: "restart web services"
Manually flush handlers early:
tasks:
   - shell: some tasks go here
   - meta: flush_handlers
   - shell: some other tasks
Define when task is marked changed:
tasks:
  - name: Copy httpd configuration
    ansible.builtin.copy:
      src: ./new_httpd.conf
      dest: /etc/httpd/conf/httpd.conf
    # The task is always reported as changed
    changed_when: True
    notify: Restart apache
Specify a role name to avoid name conflicts:
role_name : handler_name