使用Jinja2模板生成的Ansible循环列表



我使用的是Ansible,我需要循环访问存储在从文件中获得的变量中的列表(带有include_vars(。一切都很好,我可以使用各种值,只是我无法循环列表。

具体来说,我不能这样做:

---
- host: localhost
tasks:
- debug:
msg: "{{ item }}"
loop: "{{ [1,2,3,4] }}"

它喊道:";需要一个列表,得到:[1,2,4]";

但是如果我使用

loop: [1,2,3,4]

然后它工作

有人能解释一下为什么它不起作用吗?

额外信息:可靠版本:2.7.0rc2Python:3.9.2

提前感谢

由于消息

need a list, got: [1,2,3,4]

这表示变量类型不匹配,您可以引入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 }}"

以及其他用于调试的选项,例如扩展循环变量。

---
- 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 }}"

从这一秒开始,您的示例在Ansible 2.9.25中正常工作,导致的输出

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

这就引出了一个问题,你使用的是哪一个版本的Ansible?

可以复制该问题

---
- hosts: localhost
become: no
gather_facts: no
tasks:
- name: Show result
debug:
msg: "{{ item | type_debug }}"
loop: "[1,2,3,4]"

导致的输出

TASK [Show result] ***********
fatal: [localhost]: FAILED! =>
msg: 'Invalid data passed to ''loop'', it requires a list, got this instead: [1,2,3,4]

最新更新