我有以下测试手册来遍历列表字典。
- hosts: localhost
connection: local
vars:
machine_roles:
masters: ["master1","master2"]
workers: ["worker1","worker2"]
tasks:
- name: toto
debug:
msg: "{{ item.0.role}} --- {{ item.1 }}"
loop:
- "{{ machine_roles | dict2items(key_name='role', value_name='machine') | subelements('machine') }}"
我想获得以下输出:
masters --- master1
masters --- master2
workers --- worker1
workers --- worker2
根据我对文档和类似文章的理解,我希望我的剧本能够胜任这项工作。但是,运行它时出现以下错误:
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'role'\n\nThe error appears to be in '/root/git/visa-jupyter/jupyterhub-kubespawner/test.yml': line 14, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - name: toto\n ^ here\n"}
令人惊讶的是,在调试{{ machine_roles | dict2items(key_name='role', value_name='machine') | subelements('machine') }}
的结果时,我得到了:
[
[
{
"machine": [
"master1",
"master2"
],
"role": "masters"
},
"master1"
],
[
{
"machine": [
"master1",
"master2"
],
"role": "masters"
},
"master2"
],
[
{
"machine": [
"worker1",
"worker2"
],
"role": "workers"
},
"worker1"
],
[
{
"machine": [
"worker1",
"worker2"
],
"role": "workers"
},
"worker2"
]
]
在我看来,结合使用dict2items
和subelements
时,文档中将说明预期的结果。
为什么在此数据结构上应用loop
命令会失败,或者至少不会产生我期望的结果?
[编辑和答复] 我终于可以找到错误。我自己是通过以下方法引入另一个循环级别来使自己感到震惊:
loop:
- "{{ machine_roles | dict2items(key_name='role', value_name='machine') | subelements('machine') }}"
正确的语法是(出于我的目的)
loop: "{{ machine_roles | dict2items(key_name='role', value_name='machine') | subelements('machine') }}"
答案 0 :(得分:0)
这一定是一些奇怪的格式/缩进问题。您的代码工作正常
"msg": "masters --- master1"
"msg": "masters --- master2"
"msg": "workers --- worker1"
"msg": "workers --- worker2"
FWIW。这是经过测试的code的链接。