I'm using Ansible, and I need to loop over a list stored in a variable I get from a file (with include_vars). Everything is fine, I can use the various values, except I don't manage to loop over the list.
Specifically, I can't do this:
---
- host: localhost
tasks:
- debug:
msg: "{{ item }}"
loop: "{{ [1,2,3,4] }}"
It yells: "need a list, got: [1,2,3,4]"
but if I use
loop: [1,2,3,4]
Then it works
Can someone explain why it doesn't work?
Extra info: Ansible ver: 2.7.0rc2 Python: 3.9.2
Thanks in advance
Because of the message
need a list, got: [1,2,3,4]
which indicates a variable type mismatch , you may introduce the type_debug
filter
- hosts: localhost
become: no
gather_facts: no
vars:
LIST: [1, 2, 3, 4]
tasks:
- name: Show result
debug:
msg: "{{ item }} of {{ item | type_debug }}"
loop: "{{ LIST }}"
and other options for debugging, in example Extended loop variables .
---
- hosts: localhost
become: no
gather_facts: no
tasks:
- name: Show result
debug:
msg: "{{ item | type_debug }}"
loop: "{{ [1,2,3,4] }}"
loop_control:
extended: true
label: "{{ item }}"
Since this second, your example is working properly in Ansible 2.9.25, resulting into an output of
TASK [Show result] ***********
ok: [localhost] => (item=1) =>
msg: int
ok: [localhost] => (item=2) =>
msg: int
ok: [localhost] => (item=3) =>
msg: int
ok: [localhost] => (item=4) =>
msg: int
it brings up the question, which version of Ansible you are using?
The issue can be reproduced by
---
- hosts: localhost
become: no
gather_facts: no
tasks:
- name: Show result
debug:
msg: "{{ item | type_debug }}"
loop: "[1,2,3,4]"
resulting into an output of
TASK [Show result] ***********
fatal: [localhost]: FAILED! =>
msg: 'Invalid data passed to ''loop'', it requires a list, got this instead: [1,2,3,4]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.