我正在尝试使用ansible循环列表列表来安装一些软件包。但是{{item}}返回子列表中的每个元素而不是子列表本身。我有一个yaml文件来自外部ansible的清单列表,它看起来像这样:
---
modules:
- ['module','version','extra']
- ['module2','version','extra']
- ['module3','version','extra']
我的任务看起来像这样:
task:
- include_vars: /path/to/external/file.yml
- name: install modules
yum: name={{item.0}} state=installed
with_items: "{{ modules }}"
当我跑步时,我得到:
fatal: [localhost]: FAILED! => {"failed": true, "msg": "ERROR! int object has no element 0"}
当我尝试:
- debug: msg="{{item}}"
with_items: "{{module}}"
它打印每个元素(模块,版本,额外等),而不仅仅是子列表(这是我期望的)
不幸的是,这是预期的行为。请看这个discussion on with_tems and nested lists
解决此问题的另一种方法是使用复杂项而不是列表列表。像这样构造你的变量:
- modules:
- {name: module1, version: version1, info: extra1}
- {name: module2, version: version2, info: extra2}
- {name: module3, version: version3, info: extra3}
然后你仍然可以使用with_items
,像这样:
- name: Printing Stuffs...
shell: echo This is "{{ item.name }}", "{{ item.version }}" and "{{ item.info }}"
with_items: "{{modules}}"
@helloV已经提供了使用with_items
无法做到的答案,我将向您展示如何使用with_nested
的当前数据结构来获得所需的输出。
这是一个示例剧本:
---
- hosts:
- localhost
vars:
- modules:
- ['module1','version1','extra1']
- ['module2','version2','extra2']
- ['module3','version3','extra3']
tasks:
- name: Printing Stuffs...
shell: echo This is "{{ item.0 }}", "{{ item.1 }}" and "{{ item.2 }}"
with_nested:
- modules
现在您将获得以下stdout_lines
:
This is module1, version1 and extra1
This is module2, version2 and extra2
This is module3, version3 and extra3
将with_items: "{{ modules }}"
替换为:
with_list
porting guide):
loop: "{{ modules }}"
with_list: "{{ modules }}"
with_items:
- "{{ modules }}"
这样,您将拥有三个级别的嵌套列表,并且默认行为仅展平其中两个。