0

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.
Petr
  • 581
  • 1
  • 5
  • 16

1 Answers1

2

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.

Petr
  • 581
  • 1
  • 5
  • 16
  • This is usually done with a handler being notified. – Zeitounator Jun 05 '22 at 09:05
  • Yes, that's another option. But I needed the services to be enabled and started at specific points in the playbook. Perhaps I could have used [`flush_handlers`](https://docs.ansible.com/ansible/latest/user_guide/playbooks_handlers.html#controlling-when-handlers-run). – Petr Jun 05 '22 at 10:21