简体   繁体   中英

Ansible: Create dictionary from an intent file

"ABC":
  "ABC-C01":
     - host: "ABC-cn0001"
       ipv4: "xxx.xxx.xxx.xxx"
       netmask: "xxx.xxx.xxx.xxx"
       gateway: "xxx.xxx.xxx.xxx"    
       prefixlen: "19"
     - host: "ABC-cn0002"
       ipv4: "xxx.xxx.xxx.xxx"
       netmask: "xxx.xxx.xxx.xxx"
       gateway: "xxx.xxx.xxx.xxx"
       prefixlen: "19"
"DEF":
  "DEF-C01":
     - host: "DEF-cn0001"
       ipv4: "xxx.xxx.xxx.xxx"
       netmask: "xxx.xxx.xxx.xxx"
       gateway: "xxx.xxx.xxx.xxx"
       prefixlen: "19"
     - host: "DEF-cn0002"
       ipv4: "xxx.xxx.xxx.xxx"
       netmask: "xxx.xxx.xxx.xxx"
       gateway: "xxx.xxx.xxx.xxx"
       prefixlen: "19"

My expected answer below from the intent file:

{
'ABC-C01': ['ABC-cn0001.myhost.com','ABC-cn0002.myhost.com'],
'DEF-C01':['DEF-cn0001.myhost.com','DEF-cn0002.myhost.com']
}

I was able to get the list individually.

- 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'

- set_fact:
    nodes: "{{ nodes|default([]) + myfile[item[0]][item[1]] }}"
  with_nested:
    - "{{ dc}}"
    - "{{ cl}}"
  when: item[1] in myfile[item[0]].keys()

gives 'ABC-cn0001','ABC-cn0002'

But I need to get a proper dictionary with corresponding host values with the CL with the host with "mydomain.com" by processing the file.

Output looks:

{
'ABC-C01': ['ABC-cn0001.myhost.com','ABC-cn0002.myhost.com'],
'DEF-C01':['DEF-cn0001.myhost.com','DEF-cn0002.myhost.com']
}

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, `.myhost.com`])]'

gives what you want

  myfile_groups:
    ABC-C01:
    - ABC-cn0001.myhost.com
    - ABC-cn0002.myhost.com
    DEF-C01:
    - DEF-cn0001.myhost.com
    - DEF-cn0002.myhost.com

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM