Ansible:树结构上的交互

2024-06-14 02:08:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我想迭代树结构。

如何仅迭代level1和level2?(我希望看到name和level0之间的相关性如下图所示)

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

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

Tags: nametestjson列表结构dict树结构hosts
1条回答
网友
1楼 · 发布于 2024-06-14 02:08:50

有四个嵌套列表。因此,需要两个嵌套循环,都带有子元素。例如,使用文件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: "Maybe the structure is wrong ? ( json | list of dict or other ?)"

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

相关问题 更多 >