ansible with_items列表列表正在变平

问题描述 投票:12回答:4

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

它打印每个元素(模块,版本,额外等),而不仅仅是子列表(这是我期望的)

yaml ansible
4个回答
6
投票

不幸的是,这是预期的行为。请看这个discussion on with_tems and nested lists


11
投票

解决此问题的另一种方法是使用复杂项而不是列表列表。像这样构造你的变量:

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

4
投票

@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

4
投票

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

  • 在Ansible 2.5及更高版本中(参考with_list porting guide): loop: "{{ modules }}"
  • 在Ansible 2.0及更高版本中: with_list: "{{ modules }}"
  • 在任何Ansible pre-2.0中: with_items: - "{{ modules }}" 这样,您将拥有三个级别的嵌套列表,并且默认行为仅展平其中两个。
© www.soinside.com 2019 - 2024. All rights reserved.