我正在尝试从文件加载字典变量,但无法访问里面的变量。你能帮我吗?抱歉,问题这么简单
以下是一个有效的代码示例:
---
tasks:
- name: Dict test
vars:
users:
alice:
name: Alice Appleworth
telephone: 123-456-7890
bob:
name: Bob Bananarama
telephone: 987-654-3210
debug:
msg: "User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
loop: "{{ lookup('dict', users) }}"
但是当我将字典添加到文件并使用include_vars加载它时,上述代码不起作用。
文件:test1.yml
users:
alice:
name: Alice Appleworth
telephone: 123-456-7890
bob:
name: Bob Bananarama
telephone: 987-654-3210
以下代码不起作用
tasks:
- name: Dict test
include_vars: test1.yml
debug:
msg: "User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
loop: "{{ lookup('dict', users) }}"
但 ansible dubuging -vvv 显示
ok: [localhost] => {
"ansible_facts": {
"users": [
{
"alice": null,
"name": "Alice Appleworth",
"telephone": "123-456-7890"
},
{
"bob": null,
"name": "Bob Bananarama",
"telephone": "987-654-3210"
}
]
},
答案1
“不起作用”是对您的问题的一个非常模糊的描述,但这不是一个有效的任务定义:
- name: Dict test
include_vars: test1.yml
debug:
msg: "User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
loop: "{{ lookup('dict', users) }}"
include_vars
并且debug
是单独的操作,因此它们需要是单独的任务;正如您所看到的,这应该会给您有用的错误ERROR! conflicting action statements: include_vars, debug
- include_vars: test1.yml
- name: Dict test
debug:
msg: "User {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
loop: "{{ users | dict2items }}"