1

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}}
techraf
  • 64,883
  • 27
  • 193
  • 198
A.Jac
  • 1,443
  • 3
  • 17
  • 24

1 Answers1

6

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 }}"
techraf
  • 64,883
  • 27
  • 193
  • 198
  • ansible-lint warns *[ANSIBLE0016] Tasks that run when changed should likely be handlers* and Ansible Galaxy Syntax Score reports *E503: Tasks that run when changed should likely be handlers* – Vladimir Botka Nov 18 '18 at 06:54
  • The task shall be put into the handlers section. [Example](https://stackoverflow.com/questions/25694249/ansible-using-with-items-with-notify-handler) – Vladimir Botka Nov 18 '18 at 08:07