我有这个剧本:
- name: "This works"
hosts: localhost
tasks:
- debug:
msg: "{{ lookup('dict', foo) | map(attribute='key') | list}}"
vars:
foo:
bar:
type: v1
baz:
type: v2
- name: "This does not work"
hosts: localhost
tasks:
- debug:
msg: "{{ lookup('dict', foo) | map(attribute='key') | list}}"
vars:
foo:
bar:
type: v1
运行它时,我得到以下输出:PLAY [This works] *******************************************************************************************************************************************************************************************************************************
TASK [Gathering Facts] **************************************************************************************************************************************************************************************************************************
ok: [localhost]
TASK [debug] ************************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"msg": [
"bar",
"baz"
]
}
PLAY [This does not work] ***********************************************************************************************************************************************************************************************************************
TASK [Gathering Facts] **************************************************************************************************************************************************************************************************************************
ok: [localhost]
TASK [debug] ************************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
"msg": "[AnsibleUndefined, AnsibleUndefined]"
你看,它打印出 bar
和 baz
作为第一个示例中的列表,而不是仅包含 bar
的列表在第二个例子中,我得到了一些 AnsibleUndefined
输出。我需要更改什么才能使这些过滤器也适用于单项字典?
最佳答案
这是因为 lookup
并不总是返回一个列表。在第二种情况下,如果您进行调试,您会看到它返回一个不在列表中的对象:
{
"key": "bar",
"value": {
"type": "v1"
}
}
解决问题的2个解决方案:lookup
你想要一个列表 msg: {{ lookup('dict', foo, wantlist=true) | map(attribute='key') | list }}
query
代替 lookup
它总是返回一个列表,更适合这种处理(循环、映射)msg: {{ query('dict', foo) | map(attribute='key') | list }}
引用:关于Ansible 查找过滤器仅在 hashmap 中有多个项目时才起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67404713/