在Ansible中,可以使用循环和更新字典来处理复杂的任务和数据结构。以下是一个包含代码示例的解决方法:
- name: Update dictionary with loop
hosts: localhost
gather_facts: no
vars:
my_dict:
key1: value1
key2: value2
tasks:
- name: Loop through list and update dictionary
set_fact:
my_dict: "{{ my_dict|combine({item.key: item.value}) }}"
with_items:
- { key: new_key1, value: new_value1 }
- { key: new_key2, value: new_value2 }
- name: Print updated dictionary
debug:
var: my_dict
- name: Update dictionary with loop
hosts: localhost
gather_facts: no
vars:
my_dict:
key1: value1
key2: value2
update_dict:
new_key1: new_value1
new_key2: new_value2
tasks:
- name: Loop through dictionary and update another dictionary
set_fact:
my_dict: "{{ my_dict|combine({item.key: item.value}) }}"
with_dict: "{{ update_dict }}"
- name: Print updated dictionary
debug:
var: my_dict
在这两个示例中,我们使用Ansible的set_fact模块来更新字典。通过结合使用combine过滤器,我们可以将遍历的值合并到原始字典中。最后,使用debug模块打印更新后的字典。
请注意,以上只是示例代码,您可以根据自己的需求进行修改和扩展。
上一篇:Ansible循环返回整个对象
下一篇:Ansible循环和子字典