[英]Ansible loop over list generated with Jinja2 template
I'm using Ansible, and I need to loop over a list stored in a variable I get from a file (with include_vars).我正在使用 Ansible,我需要遍历存储在我从文件(使用 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]"它大喊:“需要一个列表,得到:[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额外信息:Ansible 版本: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这表明变量类型不匹配,您可以引入
type_debug
过滤器
- 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 .和其他调试选项,例如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从这一秒开始,您的示例在 Ansible 2.9.25 中正常工作,导致 output
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?它提出了一个问题,您使用的是哪个版本的 Ansible?
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导致 output 的
TASK [Show result] ***********
fatal: [localhost]: FAILED! =>
msg: 'Invalid data passed to ''loop'', it requires a list, got this instead: [1,2,3,4]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.