【发布时间】:2019-12-16 20:22:53
【问题描述】:
我正在尝试使用 Ansible 循环遍历嵌套的 dict 并添加一个新的键:值。我可以使用 combine 将值添加到顶级字典,但不确定如何更新值字典。我看到可以使用循环来遍历字典,但是如何同时进行更新?
我的字典
{'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: Iterate and update dict
set_fact:
my_dict: '{{my_dict|combine({"location": "building-a"})}}'
- debug: var=my_dict
更新后所需的字典:
{'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'}}
【问题讨论】:
标签: python loops dictionary ansible ansible-2.x