3

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.

user1712037
  • 31
  • 1
  • 3

2 Answers2

1

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
Gerald Schneider
  • 19,757
  • 8
  • 52
  • 79
1

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 }}"
Zeitounator
  • 1,090
  • 4
  • 12