【问题标题】:Ansible with_subelements nested levelsAnsible with_subelements 嵌套级别
【发布时间】:2018-09-21 03:51:39
【问题描述】:

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

Ansible with_subelements

不过,我需要更深一层。那里的评论(日期为 2017 年 1 月)指出不支持额外的嵌套级别。现在还是这样吗?如果没有,我如何参考更深层次的?

我的数据:

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

区域、用户和访问策略已成功创建,因为它们不需要深入到那个额外的级别(记录级别)。

【问题讨论】:

    标签: arrays list loops nested ansible


    【解决方案1】:

    如果您不需要根字典中的name 和prefix,您可以将原始列表缩减为简单的区域列表:

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

    And – no – 嵌套子元素仍然不受支持。

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

    - 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 列表。第二个任务是相同的,但我们循环生成的列表。

    【讨论】:

    • 这很完美——只有其他任务需要名称和前缀。非常感谢!
    猜你喜欢
    • 2017-06-14
    • 1970-01-01
    • 2011-07-27
    • 2014-04-04
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多