Skip to content Skip to sidebar Skip to footer

Ansible Loop And Update Dict

I'm trying to use Ansible to loop through a nested dict and add a new key:value. I'm able to add a value using combine to the top-level dict but unsure how to update the value dic

Solution 1:

You'll need to use the recursive argument to the combine filter, like this:

-hosts:localhostgather_facts:falsevars:my_dict:host-a: {'os':'Linux', 'port':'22', 'status':'Running'}
      host-b: {'os':'Linux', 'port':'22', 'status':'Running'}
      host-c: {'os':'Linux', 'port':'22', 'status':'Running'}

  tasks:-name:updatedictset_fact:my_dict:"{{ my_dict|combine({item: {'location': 'building-a'}}, recursive=true) }}"loop:"{{ my_dict|list }}"-debug:var:my_dict

The above playbook will output:


PLAY [localhost] *************************************************************************************************************************************************************

TASK [update dict] ***********************************************************************************************************************************************************
ok: [localhost] => (item=host-a)
ok: [localhost] => (item=host-b)
ok: [localhost] => (item=host-c)

TASK [debug] *****************************************************************************************************************************************************************
ok: [localhost] => {
    "my_dict": {
        "host-a": {
            "location": "building-a",
            "os": "Linux",
            "port": "22",
            "status": "Running"
        },
        "host-b": {
            "location": "building-a",
            "os": "Linux",
            "port": "22",
            "status": "Running"
        },
        "host-c": {
            "location": "building-a",
            "os": "Linux",
            "port": "22",
            "status": "Running"
        }
    }
}

PLAY RECAP *******************************************************************************************************************************************************************
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

Post a Comment for "Ansible Loop And Update Dict"