I have a basic role that will use hostvars from multiple files within group_vars titled with their group names to look at the sitecode and location of a particular office;
- vars:
code_location: []
set_fact:
code_location: "{{ code_location | combine({item[0]: item[1]}) }}"
with_nested:
- "{{ hostvars[inventory_hostname].sitecode }}"
- "{{ hostvars[inventory_hostname].location }}"
delegate_to: 127.0.0.1
Below is the output of that particular set_fact and looks exactly how I want it to;
Problem is passing that into a single reusable lust that will match on key|value i.e.
set_fact:
site_code: "{{ code_location.0 }}" # e.g. - ams01
when: "{{ code_location.1 == var_passed }}" # e.g. - Amsterdam
What I cannot figure out is putting this full list into a usable dictionary or list that does not depend on the host it was sourced from and that does not get overwritten with the final entry in the nested loop.
PLAY [Locations -> Sitecodes]
TASK [set_fact]
ok: [ams01-host -> 127.0.0.1] => (item=[u'ams01', u'Amsterdam'])
ok: [aus01-host -> 127.0.0.1] => (item=[u'aus01', u'Austin'])
ok: [blr01-host -> 127.0.0.1] => (item=[u'blr01', u'Bangalore'])
ok: [dub01-host -> 127.0.0.1] => (item=[u'dub01', u'Dublin'])
ok: [dus01-host -> 127.0.0.1] => (item=[u'dus01', u'Dusseldorf'])
ok: [gru01-host -> 127.0.0.1] => (item=[u'gru01', u'Sao Paulo'])
ok: [hyd01-host -> 127.0.0.1] => (item=[u'hyd01', u'Hyderabad'])
ok: [lon01-host -> 127.0.0.1] => (item=[u'lon01', u'London'])
ok: [nrt01-host -> 127.0.0.1] => (item=[u'nrt01', u'Tokyo'])
ok: [nyc01-host -> 127.0.0.1] => (item=[u'nyc01', u'New York'])
ok: [par01-host -> 127.0.0.1] => (item=[u'par01', u'Paris'])
ok: [scf01-host -> 127.0.0.1] => (item=[u'scf01', u'Scottsdale'])
ok: [sea01-host -> 127.0.0.1] => (item=[u'sea01', u'Seattle'])
ok: [sfo01-host -> 127.0.0.1] => (item=[u'sfo01', u'San Francisco'])
ok: [sin01-host -> 127.0.0.1] => (item=[u'sin01', u'Singapore'])
ok: [sjc01-host -> 127.0.0.1] => (item=[u'sjc01', u'San Jose'])
ok: [sql01-host -> 127.0.0.1] => (item=[u'sql01', u'San Mateo'])
ok: [stm01-host -> 127.0.0.1] => (item=[u'stm01', u'Stamford'])
ok: [syd01-host -> 127.0.0.1] => (item=[u'syd01', u'Sydney'])
ok: [yyz01-host -> 127.0.0.1] => (item=[u'yyz01', u'Toronto'])
I think it's easier if you solve this without delegation, which introduces complications around (a) where facts are looked up and (b) where facts are defined. Instead, you can loop over the hosts in a group like this:
---
- hosts: localhost
gather_facts: false
tasks:
- vars:
code_location: {}
set_fact:
code_location: >-
{{
code_location |
combine({hostvars[item].sitecode: hostvars[item].location})
}}
loop: "{{ groups.all }}"
The above loops over all hosts (groups.all
), but you could of course restrict that to a particular hostgroup (or even an explicit list of hosts).