3

I have an Ansible role which uses handlers to restart services via the systemd module.

- name: restart ntp
  systemd:
    name: ntp
    enabled: yes
    state: restarted
  become: true

- name: restart web server
  systemd:
    name: nginx
    enabled: yes
    state: restarted
  become: true

- name: restart grafana
  systemd:
    name: grafana
    enabled: yes
    state: restarted
  become: true

Is there a way so I could parameterize the three separate handlers into something like this?:

- name: restart {{svcname}}
  systemd:
    name: '{{svcname}}'
    enabled: yes
    state: restarted
  become: true
4

In ansible 2.7 and earlier versions, variables in handlers name are not populated.
This bug was reported and a correction was lately pushed to devel version.

You need to run ansible from devel, and hope they publish this fix in the next release.

  • How unfortunate for me, so I'll have to wait until 2.8 becomes the new stable. I am tracking the stable version already via their official PPA. – 0xC0000022L Nov 27 '18 at 13:26
0

You could set a fact to be the list of services you need restarted by the handlers:

- name: Tag services to restart
  set_fact:
    services_to_restart:
     - ntp
     - nginx
     - grafana

then your handler becomes:

- name: Restart tagged services
  service:
    name: "{{ item }}"
    state: restarted
  loop: "{{ services_to_restart }} | default('nginx')"

I suggest using a sane default there in case you send an empty list to the service module.

  • 1
    This will restart all the services for each notification – storm Nov 27 '18 at 12:55
  • That's why you only put the ones you want in the variable – Bruce Becker Nov 27 '18 at 12:56
  • But if a task needs only a restart of ntp, nginx and grafana will be restarted too .. – storm Nov 27 '18 at 13:06
  • @BruceBecker thank you. But this defies the whole purpose of handlers, doesn't it? In order to figure out whether I have to place a particular service name into the list, I'd have to first register a uniquely-named variable and then check whether that task changed anything in a subsequent set_fact task. The point of handlers is to make this whole process seamless and low-maintenance. I'd lose all that by using something like your proposed method, even though it may be technically viable. – 0xC0000022L Nov 27 '18 at 13:24
  • ok, good points. The answer by @storm is also more correct, so I suggest you accept that one as the "correct" one. – Bruce Becker Nov 27 '18 at 14:26

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.