本文介绍了Ansible with_subelements嵌套级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遍历嵌套循环,就像这个问题一样:

I'm trying to iterate through nested loops, much like this question:

Ansible with_subelements

我需要进一步深入.此处的评论(日期为2017年1月)指出,不支持其他级别的嵌套.还是这样吗?如果没有,我该如何参考更深层次的内容?

I need to go an extra level deep though. The comment there (dated January 2017) states that additional levels of nesting are unsupported. Is this still the case? If not, how can I reference deeper levels?

我的数据:

dns:
  - name: Something
    prefix: st
    zones:
      - zone: something.com
        records:
          - record: testing.something.com
            type: TXT
            value: '"somethingtest"'
            ttl: 60

  - name: Devthing
    prefix: dt
    zones:
      - zone: devthing.com
        records:
          - record: testing.devthing.com
            type: TXT
            value: '"devthingtest"'
            ttl: 60
      - zone: testthing.com
        records:
          - record: testing.testthing.com
            type: TXT
            value: '"testthingtest"'
            ttl: 60
          - record: thingy.testthing.com
            type: TXT
            value: '"testthingthingytest"'
            ttl: 60

我的任务:

- name: Create DNS records
  route53:
    state: present
    zone: "{{ item.0.zone }}"
    record: "{{ item.1.record }}"
    type: "{{ item.1.type }}"
    ttl: "{{ item.1.ttl }}"
    value:  "{{ item.1.value }}"
  with_subelements:
    - "{{ dns }}"
    - records

成功创建了区域,用户和访问策略,因为它们不需要再深入(记录级别)了.

Zones, users and access policies are successfully created since they don't need to go that extra level deep (records level).

推荐答案

如果您不需要根字典中的nameprefix,则可以将原始列表简化为区域的简单列表:

If you don't need name and prefix from root dict, you can reduce original list to plain list of zones:

with_subelements:
  - "{{ dns | map(attribute='zones') | list | sum(start=[]) }}"
  - records

而且-不-仍然不支持嵌套子元素.

And – no - nested subelements is still not supported.

更新(如果需要父选项),则需要进行一些预处理:

Update in case parent options are required, some preprocessing is required:

- set_fact:
    zones_loop: >
      {{ zones_loop|d([])
        + [ {} | combine(item[0]) | combine(item[1]) ]
      }}
  with_subelements:
    - "{{ dns }}"
    - zones

- debug:
    msg: "{{ item }}"
  with_subelements:
    - "{{ zones_loop }}"
    - records

在第一个任务中,我们遍历每个zone,并将父级的键附加/组合到它们上,从而形成新的zones_loop列表.第二项任务是相同的,但是我们遍历了生成的列表.

With first task we loop over each zone and attach/combine parent's keys to them, forming new zones_loop list. Second task is the same, but we loop over our generated list.

这篇关于Ansible with_subelements嵌套级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 15:42