---
- hosts: test
tasks:
- name: print phone details
debug: msg="user {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
with_dict: users
vars:
users:
alice: "Alice"
telephone: 123
当我运行这个剧本时,我收到此错误:
One or more undefined variables: 'dict object' has no attribute 'name'
这个实际上工作得很好:
debug: msg="user {{ item.key }} is {{ item.value }}"
我错过了什么?
这不是完全相同的代码。如果你仔细看看这个例子,你会发现在users
下你有几个词。
在你的情况下,你有两个dicts,但只有一个键(alice
,或telephone
),各自的值为“Alice”,123。
你宁愿这样做:
- hosts: localhost
gather_facts: no
tasks:
- name: print phone details
debug: msg="user {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
with_dict: users
vars:
users:
alice:
name: "Alice"
telephone: 123
(请注意,我将主机更改为localhost
,因此我可以轻松运行它,并添加了gather_facts: no
,因为这里没有必要.YMMV。)
小修正:
- name: print phone details
debug: msg="user {{ item.key }} is {{ item.value.name }} ({{ item.value.telephone }})"
with_dict: "{{ users }}" <<<<<<<<<<<<<<<<
您想要打印{{ item.value.name }}
但名称未定义。
users:
alice: "Alice"
telephone: 123
应该被替换
users:
name: "Alice"
telephone: 123
然后name
和telephone
属性都在dict(用户)中定义。