Ansible: Create dictionary from an intent file

Viewed 39
shell> cat myfile.yml
"ABC":
    "ABC-C01":
       - host: "a1"
         prefixlen: "19"
       - host: "a2"
         prefixlen: "19"
"DEF":
    "DEF-C01":
       - host: "d1"
         prefixlen: "19"
       - host: "d2"
         prefixlen: "19"

My expected answer below from the intent file :

  ABC-C01:
    - a1.domain
    - a2.domain
  DEF-C01:
    - d1.domain
    - d2.domain

I was able to get the list individually.

- include_vars:
    file: myfile.yml
    name: myfile
- set_fact:
    dc: "{{ myfile.keys()|list }}"

Gives: 'ABC' and 'DEF'

- set_fact:
    cl: "{{ cl|default([]) + myfile[item].keys()|list }}"
  with_items: "{{ dc}}"

Gives: 'ABC-C01' and 'DEF-C01'

1 Answers

Put the below declarations into the vars

myfile: "{{ lookup('file', 'myfile.yml')|from_yaml }}"
myfile_groups: "{{ dict(myfile.values()|
                        map('dict2items')|
                        json_query(_query)) }}"
_query: '[].[key, value[].join(``,[host, `.domain`])]'

gives what you want

myfile_groups:
  ABC-C01:
    - a1.domain
    - a2.domain
  DEF-C01:
    - d1.domain
    - d2.domain
Related