Ansible:Interate over tree structure

问题描述 投票:1回答:1

我想遍历树结构。

如何仅迭代级别1和级别2? (我想看到在name和level0之间显示如下所示的Corelation)

也许结构是错误的? (json |字典或其他列表?)

---
- name: test
  hosts: localhost
  gather_facts: no
  vars:
   directories:
    - name: DIR1
      level0:
       - name: SUBDIR1
         level1:
           - name: SUBDIR11
             level2:
              - name: SUBDIR111
              - name: SUBDIR112
           - name: SUBDIR12
             level2:
              - name: SUBDIR121
              - name: SUBDIR122
       - name: SUBDIR2
       - name: SUBDIR3
    - name: DIR2
      level0:
       - name: SUBDIR1
       - name: SUBDIR2
       - name: SUBDIR3

  tasks:
  - name: Debug level0
    debug:
      msg: "DIR {{item.0.name}} Subdir {{item.1.name}}"
    loop: "{{ directories | subelements('level0') }}"
python loops tree ansible
1个回答
0
投票

有四个列表嵌套。因此,需要两个带有子元素的嵌套循环。例如,对于文件loop-item.yml

中包含的任务
shell> cat loop-item.yml
- debug:
    msg: "{{ outer_item.0.name }} {{ outer_item.1.name }} {{ item.0.name }} {{ item.1.name }}"
  loop: "{{ outer_item.1.level1|default([])|subelements('level2') }}"

任务

  - include_tasks: loop-item.yml
    loop: "{{ directories|subelements('level0') }}"
    loop_control:
      loop_var: outer_item

给出嵌套列表的分解

    "msg": "DIR1 SUBDIR1 SUBDIR11 SUBDIR111"
    "msg": "DIR1 SUBDIR1 SUBDIR11 SUBDIR112"
    "msg": "DIR1 SUBDIR1 SUBDIR12 SUBDIR121"
    "msg": "DIR1 SUBDIR1 SUBDIR12 SUBDIR122"

Q:“也许结构是错误的?(json |字典或其他列表)?

A:结构很好。只能迭代列表。无论如何,任何其他结构都必须转换为列表。

© www.soinside.com 2019 - 2024. All rights reserved.