Score:2

Using variable lists in ansible returns undefined variable

ph flag

Here is my variable list file vars/blah.yml:

---
stuff:
 - stuff1: bill
   stuff2: sue

I just trying to get the values of the variable stuff.

Here's my playbook:

  hosts: all
  become: yes
  vars_files:
    - vars/blah.yml
  tasks:

  - name: test
    debug:
      var: "{{ item.stuff1 }} {{ item.stuff2 }}"
    loop :
      - "{{ stuff }}"

I'm getting this error.

fatal: [node1]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'stuff1'\n\nThe error appears to be in '/home/automation/plays/test1.yml': line 11, column 5, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n  - name: test\n    ^ here\n"}

Can someone tell me what I'm doing wrong?

Edited the formatting on the variables. Still getting the same results.

Score:1
in flag

The format of your variable file is wrong. The top level is not a list, it should look like this:

---
stuff:
  - stuff1: bill
    stuff2: sue

Additionally, the path to the vars file should start with a / from the Ansible root:

vars_files:
  - /vars/blah.yml
ph flag
Changed the formatting and same error.
Score:1
fr flag

TL;DR

  loop: "{{ stuff }}"

Full story

On the contrary of the former and still widely defaulty used with_items:, a bare loop: does not apply an automatic flatten(level=1) on the passed arguments.

For further info about this feature, you can see:

If your example was using with_items

  with_items: 
    - "{{ stuff }}"

the resulting list would still be exactly the one you defined in your file.

Now used with loop

  loop:
    - "{{ stuff }}"

you are looping over a list of lists which looks like (note the solo dash on top of the below example and the indentation of the rest of the content: it's not a typo).

- 
  - stuff1: bill
    stuff2: sue

So the first element you get in your loop is actually your full list in your var file.

To fix that, just pass the variable correctly to loop, i.e.

  loop: "{{ stuff }}"
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.