Trigger one of a set of handlers

I’m writing a fairly typical role to install and configure Apache.

  • If the primary httpd.conf file is changed, I need to “restart” Apache. This ends up running the usual service httpd restart or systemctl restart httpd command.

  • If an SSL key/cert file is updated, I need to “reload” Apache. This involves running service httpd reload or systemctl reload httpd, which tells the running Apache process to re-read those files from disk and start using them, without breaking any existing connections (the app involved uses websockets, which means long-lived connections, and restarting Apache causes dozens to thousands of clients to try and re-connect all at once, not happy fun times.)

Is there a way to ensure that, if both types of files are updated, ONLY the restart happens? Doing a reload immediately after starting or restarting Apache just wastes time and CPU cycles, because it will already have the “new” key/cert files in memory.

Also, is there a way to control the sequence in which the handlers are executed? Is it based on the order they appear in the handlers/main.yml file? The order of the tasks which “trigger” each handler? Alphabetical order based on the handler’s name? Phase of the moon?

I’m thinking if I can do something like register : apache_restarted on the “restart” handler, I can add when : not apache_restarted (not sure about the syntax, but the idea should be obvious) to the “reload” handler, so that if “restart” happened, “reload” would not. (Or can you even have a when: clause on a task which is called as a handler?)

1 Like

Also, is there a way to control the sequence in which the handlers are executed? Is it based on the order they appear in the handlers/main.yml file? The order of the tasks which “trigger” each handler? Alphabetical order based on the handler’s name? Phase of the moon?

From Handlers: running operations on change — Ansible Documentation

Handlers are executed in the order they are defined in the handlers section, not in the order listed in the notify statement.

So all handlers (including the ones from roles) are inserted into the play’s global namespace and when notified the order of execution is the order they are added into the play. See the documentation linked above for additional information.

1 Like