我正在尝试使用ansible循环列表列表来安装一些软件包.但是{{item}}返回子列表中的每个元素而不是子列表本身.我有一个yaml文件来自外部ansible的清单列表,它看起来像这样:
---
modules:
- ['module','version','extra']
- ['module2','version','extra']
- ['module3','version','extra']
Run Code Online (Sandbox Code Playgroud)
我的任务看起来像这样:
task:
- include_vars: /path/to/external/file.yml
- name: install modules
yum: name={{item.0}} state=installed
with_items: "{{ modules }}"
Run Code Online (Sandbox Code Playgroud)
当我跑步时,我得到:
fatal: [localhost]: FAILED! => {"failed": true, "msg": "ERROR! int object has no element 0"}
Run Code Online (Sandbox Code Playgroud)
当我尝试:
- debug: msg="{{item}}"
with_items: "{{module}}"
Run Code Online (Sandbox Code Playgroud)
它打印每个元素(模块,版本,额外等),而不仅仅是子列表(这是我期望的)
gam*_*eld 13
解决此问题的另一种方法是使用复杂项而不是列表列表.像这样构造你的变量:
- modules:
- {name: module1, version: version1, info: extra1}
- {name: module2, version: version2, info: extra2}
- {name: module3, version: version3, info: extra3}
Run Code Online (Sandbox Code Playgroud)
然后你仍然可以使用with_items
,像这样:
- name: Printing Stuffs...
shell: echo This is "{{ item.name }}", "{{ item.version }}" and "{{ item.info }}"
with_items: "{{modules}}"
Run Code Online (Sandbox Code Playgroud)
@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
Run Code Online (Sandbox Code Playgroud)
现在您将获得以下内容stdout_lines
:
This is module1, version1 and extra1
This is module2, version2 and extra2
This is module3, version3 and extra3
Run Code Online (Sandbox Code Playgroud)
替换with_items: "{{ modules }}"
为:
在 Ansible 2.5 及更高版本中(请参阅with_list
移植指南):
loop: "{{ modules }}"
Run Code Online (Sandbox Code Playgroud)在 Ansible 2.0 及更高版本中:
with_list: "{{ modules }}"
Run Code Online (Sandbox Code Playgroud)在任何 Ansible 2.0 之前的版本中:
with_items:
- "{{ modules }}"
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您将拥有三层嵌套列表,并且默认行为只会展平其中的两个。
归档时间: |
|
查看次数: |
28425 次 |
最近记录: |