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

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

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

- name: restart grafana
    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}}
    name: '{{svcname}}'
    enabled: yes
    state: restarted
  become: true

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.


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

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

then your handler becomes:

- name: Restart tagged services
    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 agree to our terms of service, privacy policy and cookie policy

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