Score:0

referencing variables from defaults/main.yml in ansible role

ag flag

I have a role setup as follows

roles/test/task/main.yml

- name: Generate people files
  template: src=test.j2 dest=/tmp/{{ item.name}}.cfg
  loop: "{{people}}"

roles/test/template/test.j2

First Var: {{ item.var1 }}
Second Var: {{ item.var2 }}

roles/test/vars/main.yml

---
people:
        - name: TheSimpsons
          var1: homer
          var2: simpson

        - name: StarWars
          var1: han
          var2: solo

roles/test/defaults/main.yml

people:
   - var2: skywalker

my playbook

 - hosts: localhost
   roles:
    - test

When I run my playbook everything works as expect. I get two new files in /tmp with the correct text. However if I remove this var2 line from my vars/main.yml file...

          var2: solo

I would expect the var2 value from my defaults/main.yml to show up in the output, but all I get is this error

failed: [localhost] (item={u'var1': u'han', u'name': u'StarWars'}) => {
    "changed": false,
    "item": {
        "name": "StarWars",
        "var1": "han"
    },
    "msg": "AnsibleUndefinedVariable: 'dict object' has no attribute 'var2'"
}

I have tried formatting my defaults/main.yml about 10 different ways but get the same error each time.

If I setup a test that doesn't loop and defaults/main.yml and vars/main.yml are flat "key: value" pairs I can get it to pull values from defaults/main/yml just fine.

Something about the looping I'm just not getting. What am I doing wrong?

U880D avatar
ca flag
This question became answered at https://stackoverflow.com/a/71162073/6771046.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.