Search code examples
ansiblejinja2ansible-2.xansible-template

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


Solution

  • The data in YAML

      result:
        containers:
          - Image: ca.docker/webproxy:1.0.0
            Names:
              - /customer1
          - Image: docker.local/egacustomer:1.0.1
            Names:
              - /registrator
    

    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