Ansible in a Minute · Ansible Core ·
Use variables in handler parameters
Short answer
Put the service name in the handler module arguments. Do not put a variable in the handler name.
Subscribe for updates
Get an email whenever we publish new guides and blog posts. Unsubscribe anytime.
By subscribing you agree we may email you about Ansible in a Minute and related Level Up Labs updates. We store your address in the same lead sheet as our contact form.
Request
notify Restart web service and use web_service_name | default httpd
Example
A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.
---
- name: Teach using variables with handlers
hosts: all
gather_facts: true
become: true
tasks:
- name: Include distribution facts
ansible.builtin.include_vars:
file: "{{ ansible_facts.distribution }}.yml"
- name: Template config file
ansible.builtin.template:
src: config.j2
dest: /etc/web_service/config.conf
mode: "0644"
notify: Restart web service
handlers:
- name: Restart web service
ansible.builtin.service:
name: "{{ web_service_name | default('httpd') }}"
state: restartedHow it works
Handler names are templated early. A missing variable in the name fails the play. Keep the name static. Put web_service_name on the service module.
When to use it
- Restarting a service whose package name differs by distribution
- Loading per-OS vars before a notify
Requirements
- Ansible: >=2.14
Validation
- Syntax validated
- Not execution-tested
- Last verified 2026-09-18
Notes
Do not write name: Restart "{{ web_service_name }}". Changing the variable mid-play does not create a new handler. listen topics cannot be templated.
Reference
- Using variables with handlers (Ansible docs)
Built for every Ansible use case in every organization
BacklogZero can generate this kind of automation in your environment, just like it did here.