'Ansible AnsibleUndefinedVariable no attribute

I have the following files vars/main.yml

testconfig:
 - {hostname: router123, example: no ip cef}

cisco_891_l2interfaces:
 - FastEthernet0
 - FastEthernet1
 - FastEthernet2
 - FastEthernet3
 - FastEthernet4
 - FastEthernet5
 - FastEthernet6
 - FastEthernet7

euvar:
 - {dc1: "1.1.1.1", dc2: "1.2.2.2"}

tasks main.yml

- name: Generate configuration files for DMVPN router
  template: src=router.j2 dest=/lib/python2.7/site-packages/ansible/RTR-TEMPLATE/bla/bla.txt
  with_items: testconfig

router.j2

{{item.example}}

!
boot-start-marker
boot-end-marker
!

{{euvar.dc1}}

This gives me the error, I am unsure how to reference euvar.dc1 from router.j2

    TASK: [router | Generate configuration files for DMVPN router] ****************
fatal: [localhost] => {'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'list object' has no attribute 'dc1'", 'failed': True}
fatal: [localhost] => {'msg': 'One or more items failed.', 'failed': True, 'changed': False, 'results': [{'msg': "AnsibleUndefinedVariable: One or more undefined variables: 'list object' has no attribute 'dc1'", 'failed': True}]}

FATAL: all hosts have already failed -- aborting


Solution 1:[1]

You defined euvar as a list of dicts. But you're trying to access the first list item directly. From my feeling you just want a dict like so:

euvar: {dc1: "1.1.1.1", dc2: "1.2.2.2"}

Or for those who prefer readability:

euvar:
  dc1: 1.1.1.1
  dc2: 1.2.2.2

Then you will be able to access it as {{ euvar.dc1 }}.

In case you really meant to define a list of dicts, then you can access it like @????? already commented on the question: {{ euvar[0].dc1 }}


Please also have a look at Ansibles inventory groups and group_vars. The name of your variable suggests you're working around Ansibles best practices.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sentry