Given a set of previous task whose results I register, I want to:
- Enable my target service.
- Restart/reload it when any of the dependencies have changed.
This worked for me:
- name: "Enable and (re)start service {{ service_name|mandatory }}"
systemd:
name: "{{ service_name }}"
daemon_reload: "{{ restart }}"
enabled: yes
state: "{{ restart|ternary('restarted', 'started') }}"
vars:
restart: "{{ registered|flatten|selectattr('changed')|length > 0 }}"
where registered
contains a list of the registered dependencies, as in:
vars:
registered: "{{ [registered_outcome_1, ...] }}"
The |flatten
expression ensures that it also works with looped tasks.
I also found useful to combine this with looking up the registered variables by their names so that I can just list names of registered variables instead of constructing the a list using {{ [ ... ] }}
.
Even a nicer solution would be to run systemctl reload-or-restart ...
:
Reload one or more units if they support it. If not, stop and then start them instead. If the units are not running yet, they will be started.
But this isn't supported by Ansible at the moment.