BacklogZero®

Ansible in a Minute · Ansible Core ·

Use notify in a loop to target dynamic handlers

Short answer

Use notify with item in a loop so each changed template can notify a matching 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

template memcached and apache units and notify Restart item handlers

Example

A quick heads-up: Every environment is different. Review and test this example before you run it on systems you care about.

YAML
---
- name: Template services and notify matching handlers
  hosts: all
  become: true
  gather_facts: false
  tasks:
    - name: Template services
      ansible.builtin.template:
        src: "{{ item }}.j2"
        dest: "/etc/systemd/system/{{ item }}.service"
      notify: "Restart {{ item }}"
      loop:
        - memcached
        - apache

  handlers:
    - name: Restart memcached
      ansible.builtin.service:
        name: memcached
        state: restarted

    - name: Restart apache
      ansible.builtin.service:
        name: apache
        state: restarted

How it works

A looped task can notify handlers with a templated name. If any loop iteration reports changed, Ansible treats the task as changed and runs all notified handlers from that task.

When to use it

  • Deploying several unit files with matching restart handlers
  • Dynamic notify strings built from loop items

Requirements

  • Ansible: >=2.14

Validation

  • Syntax validated
  • Not execution-tested
  • Last verified 2026-09-16

Notes

Any changed iteration notifies every handler named by the task for that run. Plan handler names so a change to one item does not restart unrelated services unintentionally.

Reference

Built for every Ansible use case in every organization

BacklogZero can generate this kind of automation in your environment, just like it did here.

Get BacklogZero today

Related guides

Back to Ansible in a Minute

Use notify in a loop to target dynamic handlers · Level Up Labs