Sometimes it could happen that we want to run multiple tasks after configuration file has changed instead of just one.
My specific usecase is, that I’m having a role that configures a SSL-certificate and additional SSL settings for an Apache webserver which could run standalone on a server or as a pacemaker resource.
If it is running directly on the server it’s quite simple and a handler is sufficient to restart the Apache service after the role ran through. In case the Apache is running as a pacemaker resource the resource should be restarted instead of the whole service to make sure pacemaker does not get confused. Therefore it is necessary to first check if we have the service running as a pacemaker resource first and execute the corresponding task afterwards so a single task (within our handler) is not sufficient.
Using the block statement will also not lead to success but fail with : ERROR! The requested handler 'Apply Apache Config' was not found in either the main handlers list nor in the listening handlers list
My approach to tackle this issue was to “missuse” the handler to only set a variable if something changed.
At the end of the role I’m checking if the variable is ture and if so, I’m including/executing my “handler-block”.
defaults/main.yml
common_linux_zabbix_server_web_ssl_path_private_apply_apache_config: no
handlers/main.yml
---
# handlers file for common_linux_zabbix_server_web_certificate
#set a fact which is checked at the end of the role-tasks
- name: "Apply Apache Config"
set_fact:
common_linux_zabbix_server_web_ssl_path_private_apply_apache_config: yes
tasks/main.yml
---
...
all your other tasks are executed before these following tasks
...
# workaround to run multiple tasks within a handler -> run the handlers if any of the above tasks did change something to notify the handler
- meta: flush_handlers
- name: "Run multiple tasks as a handler"
include_tasks: ./restart_apache_resource_or_service.yml
tasks/restart_apache_resource_or_service.yml
---
- name: "Check if cluster resource exists"
shell: "pcs resource | grep zbx_srv_httpd"
ignore_errors: yes
register: check
- name: "Restart cluster resource:"
shell: "pcs resource restart zbx_srv_httpd"
register: resource_restart
when: check.rc == 0
- fail:
msg: "An error occured when restarting the cluster resurce!"
when: resource_restart.rc != 0
#Just restart the httpd service if no cluster resource was found
- name: "Restart httpd service"
service:
name: "httpd"
state: restarted
when: check.rc != 0[