ansible loop fail

From thelinuxwiki
Revision as of 21:31, 16 April 2025 by Nighthawk (Talk | contribs)

Jump to: navigation, search

Problem: loops were failing when trying to pass a variable with something like "foo,bar" in it. This is just a string with a comma in it.

ansible error: Invalid data passed to 'loop', it requires a list

Solution: enscapsulate with square brackets [ ] and quotes around individual elements.

example:

["foo","bar"]


Example Play

 - name: example play showing common loop/list error
 hosts: localhost
 gather_facts: false
 tasks:
   - name: set var1
     set_fact:
     var1: "foo,bar"
    
   - name: set var2
     set_fact:
     var2: ["foo","bar"]
   
   - name: output var1 type
     debug:
     msg: "{{ var1 | type_debug }}"
   
   - name: output var2 type
     debug:
     msg: "{{ var2 | type_debug }}"
   
   - name: try to loop var2
     debug:
     msg: "{{ item }}"
     loop: "{{ var2 }}"
   
   - name: try to loop var1
     debug:
     msg: "{{ item }}"
     loop: "{{ var1 }}"

$ ansible-playbook example_list.yml

PLAY [localhost] *******************************************************************************************************
 
TASK [set var1] ********************************************************************************************************
ok: [localhost]
 
TASK [set var2] ********************************************************************************************************
ok: [localhost]
 
TASK [output var1 type] ************************************************************************************************
ok: [localhost] => {
"msg": "AnsibleUnicode"
}
 
TASK [output var2 type] ************************************************************************************************
ok: [localhost] => {
"msg": "list"
}
 
TASK [try to loop var2] ************************************************************************************************
ok: [localhost] => (item=foo) => {
"msg": "foo"
}
ok: [localhost] => (item=bar) => {
"msg": "bar"
}
 
TASK [try to loop var1] ************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "Invalid data passed to 'loop', it requires a list, got this instead: foo,bar. Hint: If you passed a list/dict of just one element, try adding wantlist=True to your lookup invocation or use q/query instead of lookup."}
 
PLAY RECAP *************************************************************************************************************
localhost                  : ok=5    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0