Collecting variables from multiple hosts in a playbook

Viewed 168

I have a playbook that collects a list of information from multiple hosts, and I want to collect those lists together into a single variable. So for example, my output might look like this:

ok: [ALBSWA052] => {
    "myvar": [
        "ALBSWA052 exists",
        "ALBSWA052 is secondary"
    ]
}
ok: [ALBSWA051] => {
    "myvar": [
        "ALBSWA051 exists",
        "ALBSWA051 is primary"
    ]
}

and I'd like to combine them into a list like

    "myvar": [
        "ALBSWA052 exists",
        "ALBSWA052 is secondary"
        "ALBSWA051 exists",
        "ALBSWA051 is primary"
    ]

Is there an elegant way to do this? The only way I can think of is to write it into a file and read it back in.

1 Answers

For example

    - set_fact:
        myvar: "{{ ansible_play_hosts|map('extract', hostvars, 'myvar')|flatten }}"
      run_once: true

gives the expected result

myvar:
  - ALBSWA051 exists
  - ALBSWA051 is secondary
  - ALBSWA052 exists
  - ALBSWA052 is secondary
Related