ansible create a new dict and add to list

Viewed 180

my playbook always show me just last value , looks like the script is overwrite. From json file I need extract some value, create dictionary and put it to the list. My json file .

{
    "rade": [
        {
            "apiRawValues": {
                "verificationStatus": "signature-verified"
            },
            
            "deviceReference": {
                
                "name": "bigip02"
            },
            "port": "Ir_HTTP_HTTPs"
            
        },
        {
            "apiRawValues": {
                "verificationStatus": "signature-verified"
            },
            
            "deviceReference": {
                
                "name": "bigip01"
            },
            "port": "Ir_HTTP_HTTPs"
            
        }
    ]
}

and my playbook look like

---
- hosts: localhost
  connection: local
  gather_facts: false

  vars:
    cert1: {}
    
  vars_files:
    
     
  tasks:
 
    - name : deploy json file AS3  to F5
      set_fact:
         json_file: "{{ lookup('file', 'parse2.json') }}"

   - name: create dic and create list
      set_fact: 
        cert1: "{{ cert1 | d({}) | combine({ 'device': item['deviceReference']['name']}, { 'port': item.port},  recursive=True)  }}"
      loop: "{{ json_file['rade'] }}"

    - name: debug4
      debug:
          msg: "{{ cert1 }}"

the result is

ok: [localhost] => {
    "msg": {
        "device": "bigip01",
        "port": "Ir_HTTP_HTTPs"
    }
}

why it just show me last value ?

I need list of device and port.

thank you for help

2 Answers

The filter json_query makes it simpler e.g.

    - debug:
        msg: "{{ json_file.rade|
                 json_query('[].{device: deviceReference.name, port: port}') }}"

gives

  msg:
  - device: bigip02
    port: Ir_HTTP_HTTPs
  - device: bigip01
    port: Ir_HTTP_HTTPs

If the names of the devices are unique you can create a dictionary, e.g.

    - debug:
        msg: "{{ dict(_keys|zip(_vals)) }}"
      vars:
        _keys: "{{ json_file.rade|map(attribute='deviceReference.name')|list }}"
        _vals: "{{ json_file.rade|map(attribute='port')|list }}"

gives

  msg:
    bigip01: Ir_HTTP_HTTPs
    bigip02: Ir_HTTP_HTTPs

I have found out solution

- name: create dic and create list
  set_fact: 
    cert1: "{{ cert1 | default([]) + [{ 'device' : item['deviceReference']['name'], 'irule' : item.port }] }}"
  loop: "{{ json_file['rade'] }}"

- name: debug4
  debug:
      msg: "{{ cert1 }}"
Related