ansible with_items列表列表正在变平

Ney*_*bar 14 yaml ansible

我正在尝试使用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)


hee*_*ayl 7

@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)


hel*_*loV 6

不幸的是,这是预期的行为.请参阅有关with_tems和嵌套列表的讨论


tec*_*raf 6

替换with_items: "{{ modules }}"为: