Search code examples
ansibleansible-handlers

Ansible notify handler with_items


I'm adding JAVA_OPTS as environment variables through ansible for multiple applications, and I want to restart an application if JAVA_OPTS changed.

What I have now is a task for each application to add the environment variable and a notify to restart the application like:

- name: Add variable1
  become: yes
  lineinfile: dest=/etc/environment regexp='^VARIABLE1=' line='VARIABLE1={{VARIABLE1}}'
  notify: restart application1

- name: restart application1
  become: yes
  command: restart application1

As I have many applications doing it this way means having a lot of tasks. What I would like is to have a task to loop over the applications using with_items. What I can't figure out is how to have one handler task for restart. Is it possible to pass to the handler which application needs a restart? Something like:

- name: add variables
  become: yes
  lineinfile: dest=/etc/environment regexp='^{{item.app_name}}='
  line='{{item.app_name}}={{ item.variable }}'
  notify: restart apps   #pass app_name to handler somehow
  with_items:
  - { variable: "FIRST", app_name: "APP1"}
  - { variable: "SECOND", app_name: "APP2"}
  - { variable: "THIRD", app_name: "APP3"}


- name: restart apps
  become: yes
  command: restart {{app_name}}

Solution

  • You can emulate handler functionality yourself by registering the values and looping over them in a subsequent task (that second task may or may not be defined as a handler):

    - name: add variables
      lineinfile:
        dest: ./testfile
        regexp: '^{{item.app_name}}='
        line: '{{item.app_name}}={{ item.variable }}'
      register: add_variables
      with_items:
        - { variable: "FIRST", app_name: "APP1"}
        - { variable: "SECOND", app_name: "APP2"}
        - { variable: "THIRD", app_name: "APP3"}
    
    - name: restart apps
      become: yes
      command: restart {{item.item.app_name}}
      when: item.changed
      with_items: "{{ add_variables.results }}"