Ansible循环字典时提示无attribute_one属性,如何解决?
问题解决:Ansible循环字典时找不到attribute_one属性
问题背景
目标YAML文件内容:
--- root: children_one: attribute_one: true attribute_two: foo children_two: attribute_one: false attribute_two: bar children_three: attribute_one: false attribute_two: foo
尝试编写Playbook循环该字典,打印所有attribute_one为false的子项的attribute_two,但执行时报错提示不存在attribute_one属性,原Playbook代码:
- ansible.builtin.debug: msg: "{{ item }} - {{ item.attribute_two }}" with_items: "{{ (lookup('template', 'file.yml.j2') | from_yaml).root }}" when: (item.attribute_one | lower) == 'false'
错误原因
直接循环root字典时,item获取到的是字典的键名(如children_one),而非对应的子字典对象,因此无法访问attribute_one属性。
解决方案
方法1:循环字典的values集合
直接获取root字典的所有值(即子字典)进行循环,同时修正条件判断(YAML中的true/false是布尔类型,无需转为字符串判断):
- ansible.builtin.debug: msg: "{{ item.attribute_two }}" with_items: "{{ (lookup('template', 'file.yml.j2') | from_yaml).root.values() }}" when: not item.attribute_one
方法2:使用dict2items过滤器转换字典
将root字典转为{key: ..., value: ...}的列表,同时获取键名和子字典(适合需要显示子项名称的场景):
- ansible.builtin.debug: msg: "{{ item.key }} - {{ item.value.attribute_two }}" with_items: "{{ (lookup('template', 'file.yml.j2') | from_yaml).root | dict2items }}" when: not item.value.attribute_one
关键注意点
- 布尔值无需转字符串判断:YAML中定义的
true/false是布尔类型,直接用not item.attribute_one或item.attribute_one == false即可,避免多余的类型转换。 - 循环字典时需明确目标:根据需求选择循环键(
keys())、值(values())或键值对(dict2items)。
内容的提问来源于stack exchange,提问作者ChristianWohlgemuth
相关产品推荐
相关产品推荐

