ansible: using with_items with notify handler

To update jarv's answer above, Ansible 2.5 replaces with_items with loop. When getting results, item by itself will not work. You will need to explicitly get the name, e.g., item.name.

- hosts: localhost
  tasks:
  - file:  >
      path=/tmp/{{ item }}
      state=directory
    register: files_created
    loop:
      - one
      - two
    notify: some_handler

  handlers:
    - name: "some_handler"
      shell: "echo {{ item.name }} has changed!"
      when: item.changed
      loop: files_created.results

Variables in Ansible are global so there is no reason to pass a variable to handler. If you are trying to make a handler parameterized in a way that you are trying to use a variable in the name of a handler you won't be able to do that in Ansible.

What you can do is create a handler that loops over a list of services easily enough, here is a working example that can be tested locally:

- hosts: localhost
  tasks:
  - file:  >
      path=/tmp/{{ item }}
      state=directory
    register: files_created
    with_items:
      - one
      - two
    notify: some_handler

  handlers:
    - name: "some_handler"
      shell: "echo {{ item }} has changed!"
      when: item.changed
      with_items: files_created.results

I finally solved it by splitting the apps out over multiple instances of the same role. This way, the handler in the role can refer to variables that are defined as role variable.

In site.yml:

- hosts: localhost
  roles:
  - role: something
    name: a
  - role: something
    name: b

In roles/something/tasks/main.yml:

- name: do something
  shell: "echo {{ name }}"
  notify: something happened

- name: do something else
  shell: "echo {{ name }}"
  notify: something happened

In roles/something/handlers/main.yml:

- name: something happened
  debug:
    msg: "{{ name }}"

Seems a lot less hackish than the first solution!

Tags:

Ansible