简体   繁体   中英

Ansible: How to create nested dictionary using Jinja2

Here is the output.

"result.containers":[
{
  "Image":"ca.docker/webproxy:1.0.0",
  "Names":[
     "/customer1"
  ]
},
{
  "Image":"docker.local/egacustomer:1.0.1",
  "Names":[
     "/registrator"
  ]
}
]

I'm trying to get the following output using jinja2

"containerlist"=>{
            "webproxy": {
                "name": "customer1"
           }, 
            "egacustomer": {
                "name": "registrator"
           }
         }

Here is my jinja2 code.

- set_fact:
      containerlist: |
       {
       {% for item in result.containers %}
       {{ item.Image.split('/')[-1].split(':')[0] | replace('\n', '') }}
            name : {{ item.Names[0][1:] | replace('\n', '') }}
       {% endfor %}
       }

I get the below output.

 "containerlist": "{\nwebproxy\n     name : customer1\negacustome\n     name : registrator\n}"

Could someone please help me get the desired output. Any help would be greatly appreciated

The tasks below

    - set_fact:
        containerlist: "{{ containerlist|default({})|
                           combine({key: {'name': name}}) }}"
      loop: "{{ result.containers }}"
      vars:
        key: "{{ (item.Image.split(':')|first).split('/')|last }}"
        name: "{{ item.Names[0][1:] }}"
    - debug:
        var: containerlist

give

  containerlist:
    egacustomer:
      name: registrator
    webproxy:
      name: customer1

But, the result is not a list. It's a dictionary. If you want a list use this

    - set_fact:
        containerlist: "{{ containerlist|default([]) +
                           [{key: {'name': name}}] }}"
      loop: "{{ result.containers }}"
      vars:
        key: "{{ (item.Image.split(':')|first).split('/')|last }}"
        name: "{{ item.Names[0][1:] }}"
    - debug:
        var: containerlist

give

  containerlist:
  - webproxy:
      name: customer1
  - egacustomer:
      name: registrator

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