Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ansible: can't access dictionary value - got error: 'dict object' has no attribute

---
- 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

When I run this playbook, I am getting this error:

One or more undefined variables: 'dict object' has no attribute 'name' 

This one actually works just fine:

debug: msg="user {{ item.key }} is {{ item.value }}"

What am I missing?

like image 604
user1692261 Avatar asked Oct 29 '14 19:10

user1692261


Video Answer


1 Answers

This is not the exact same code. If you look carefully at the example, you'll see that under users, you have several dicts.

In your case, you have two dicts but with just one key (alice, or telephone) with respective values of "Alice", 123.

You'd rather do :

- 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

(note that I changed host to localhost so I can run it easily, and added gather_facts: no since it's not necessary here. YMMV.)

like image 193
leucos Avatar answered Sep 18 '22 15:09

leucos