如何解决如何在Ansible中更新字典
我正在用ansible创建一个简单的字典,
"types_dict": {
"name1": "Ethernet","name2": "Ethernet","name3": "Software-Pseudo","name4": "Ethernet","name5": "Software-Pseudo","name6": "Ethernet" }
我的目标是循环词典并用“虚拟”替换某些特定值,即“ Software-Pseudo”。我尝试了以下方法:
- set_fact:
types_dict: "{{ types_dict | combine(new_item,recursive=true) }}"
vars:
new_item: "{ '{{ item.key }}': { 'type': 'Virtual' } }"
with_dict: "{{ types_dict }}"
但是这里的问题是,这个更新了字典中的所有值,这是我根本不需要的。我还通过添加“ when”语句尝试了以下方法,但是它不起作用:
- set_fact:
types_dict: "{{ types_dict | combine(new_item,recursive=true) }}"
vars:
new_item: "{ '{{ item.key }}': { 'type': 'Virtual' } }"
when: "{{ item.value }} == Software-Pseudo"
with_dict: "{{ types_dict }}"
我也尝试了when: "{{ item.value }} == 'Software-Pseudo'"
和其他类似的事情。
关于如何解决此问题的任何想法?
解决方法
任务完成工作。如有需要,可以将项目添加到列表types_new
- set_fact:
types_dict: "{{ types_dict|combine({item.0.key: item.1.replace}) }}"
with_nested:
- "{{ types_dict|dict2items }}"
- "{{ types_new }}"
when: item.0.value is search(item.1.regex)
vars:
types_new:
- {regex: 'Software-Pseudo',replace: 'Virtual'}
- debug:
var: types_dict
给予
types_dict:
name1: Ethernet
name2: Ethernet
name3: Virtual
name4: Ethernet
name5: Virtual
name6: Ethernet
Q:“我的字典中有空值,例如“ name2”:null,我可以以任何方式处理此问题,以便用其他(另一个值)替换它。” >
A:在types_new
中添加一行。例如
vars:
types_new:
- {regex: 'Software-Pseudo',replace: 'Virtual'}
- {regex: 'None',replace: 'another_value'}
查看下面的任务,如何通过search测试对待null
,None
和'None'
- debug:
msg: "{{ item.key }} {{ item.value is search('None') }}"
loop: "{{ my_vars|dict2items }}"
vars:
my_vars:
var1: abc
var2:
var3: None
var4: 'None'
给予
msg: var1 False
msg: var2 True
msg: var3 True
msg: var4 True
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。