问题
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 dict. I see that loop can be used to iterate through the dict but how can update be done at the same time?
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'}}
I'm able to append to the top level dict but not sure how to loop through and another key:value to the nested dict list.
tasks:
- name: Iterate and update dict
set_fact:
my_dict: '{{my_dict|combine({"location": "building-a"})}}'
- debug: var=my_dict
Desired Dict after update:
{'host-a': {'os': 'Linux', 'port': '22', 'status': 'Running', 'location': 'building-a'},
'host-b': {'os': 'Linux', 'port': '22', 'status': 'Running', 'location': 'building-a'},
'host-c': {'os': 'Linux', 'port': '22', 'status': 'Running', 'location': 'building-a'}}
回答1:
You'll need to use the recursive
argument to the combine
filter, like this:
- hosts: localhost
gather_facts: false
vars:
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: update dict
set_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
来源:https://stackoverflow.com/questions/59363779/ansible-loop-and-update-dict