Ansible:无法访问字典值 - 得到错误:'dict object'没有属性

use*_*261 16 dictionary ansible

---
- 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
Run Code Online (Sandbox Code Playgroud)

当我运行这个剧本时,我收到此错误:

One or more undefined variables: 'dict object' has no attribute 'name' 
Run Code Online (Sandbox Code Playgroud)

这个实际上工作得很好:

debug: msg="user {{ item.key }} is {{ item.value }}"
Run Code Online (Sandbox Code Playgroud)

我错过了什么?

leu*_*cos 14

这不是完全相同的代码.如果你仔细看看这个例子,你会看到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
Run Code Online (Sandbox Code Playgroud)

(注意我改变了主机,localhost所以我可以轻松地运行它,并添加,gather_facts: no因为这里没有必要.YMMV.)