Running a Role handler from a playbook
If you are well organized you have multiple roles to manage you deployment and configuration
If you know the Ansible handler power you use it to manage all the operations on your software, services and so on.
It is simple to trigger a handler inside a role task, but have you ever imagined using the role handlers from outside your role tasks, from a playbook ?
If you can trigger immediately a handler from a playbook it opens multiple way of managing your software and services.
Usually you have handlers for your software or services to
- Stop
- Start
- Restart
- Reload
You use it inside role task to trigger a restart after a configuration change.
Here is the simple example from Ansible documentation
--- - name: Ensure apache is at the latest version ansible.builtin.yum: name: httpd state: latest - name: Write the apache config file ansible.builtin.template: src: /srv/httpd.j2 dest: /etc/httpd.conf notify: - Restart apache - name: Ensure apache is running ansible.builtin.service: name: httpd state: started handlers: - name: Restart apache ansible.builtin.service: name: httpd state: restarted
Here inside a role we see that using notify associated to “Restart apache” will trigger the handler to restart service httpd
If I want to call the handler from outside the role from a playbook because I have a succession of the role tasks that needs a restart of httpd service and I don’t want to restart it at each task call from the playbook but only at the last one.
Here how to proceed :
- name: Multiple apache tasks hosts: webservers tasks: - name: Write apache config file ansible.builtin.include_role: name: ansible-role-apache tasks_from: "{{ task }}" loop: - "config/app1" - "config/app2" - "config/app3" - "config/app4" - "config/app5" loop_control: loop_var: task - name: Write apache files ansible.builtin.include_role: name: ansible-role-apache tasks_from: "{{ task }}" loop: - "files/app1" - "files/app2" - "files/app3" - "files/app4" - "files/app5" loop_control: loop_var: task - name: Restart apache hosts: webservers tasks: - name: Include role only without any task running to have access to handlers ansible.builtin.include_role: name: ansible-role-apache - name: Calling role handlers ansible.builtin.debug: msg: "Restarting apache after multiple application configuration/files changes" notify: "ansible-role-apache: Restart apache" changed_when: true
This will call the handler from the playbook, very useful to organized your code and manage all software or services operations.