Ansible 通知处理程序 with_items

A.J*_*Jac 1 ansible ansible-handlers

我正在通过 ansible 为多个应用程序添加 JAVA_OPTS 作为环境变量,如果 JAVA_OPTS 更改,我想重新启动应用程序。

我现在拥有的是每个应用程序添加环境变量的任务和重启应用程序的通知,例如:

- 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
Run Code Online (Sandbox Code Playgroud)

因为我有很多应用程序这样做意味着有很多任务。我想要的是有一个任务来循环使用with_items. 我无法弄清楚如何让一个处理程序任务重新启动。是否可以将需要重新启动的应用程序传递给处理程序?就像是:

- 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}}
Run Code Online (Sandbox Code Playgroud)

tec*_*raf 5

您可以通过注册值并在后续任务中循环它们来自己模拟处理程序功能(第二个任务可能被定义为也可能不被定义为处理程序):

- 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 }}"
Run Code Online (Sandbox Code Playgroud)