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?
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 }}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With