Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Ansible handlers based on changed results in multiple loops

I have an Ansible variable containing a list of web servers (all on the same host):

servers:
  - foo
  - bar
  - baz

And a task that changes their config files, and registers the results in a variable:

- name: create server configs
  template: ...
  with_items: "{{ servers }}"
  notify: restart changed servers
  register: servers_changed

And a handler that restarts only the servers that are changed when that task runs:

- name: restart changed servers
  command: restart-my-server {{ item.item.name }}
  when: item.changed
  with_items: "{{ servers_changed.results }}"

My problem is, I now need multiple tasks like the one above, which change different config files. But if I do that, they'll overwrite the servers_changed variable, so only the last one will be used.

I could register different variables in each tasks, but then I need a different handler for each one. This would get messy. Is there a better way?

like image 991
JW. Avatar asked Dec 20 '16 00:12

JW.


1 Answers

Use servers_changed as a composite list and concatenate the results of each task:

- name: create server configs
  template: ...
  with_items: "{{ servers }}"
  notify: restart changed servers
  register: servers_changed_now

- set_fact:
    servers_changed: "{{ servers_changed | default([]) | union(servers_changed_now.results|default([]) }}"

and

- name: restart changed servers
  command: restart-my-server {{ item.item.name }}
  when: item.changed
  with_items: "{{ servers_changed }}"
like image 92
techraf Avatar answered Sep 24 '22 10:09

techraf