问题描述
我正在尝试遍历嵌套循环,就像这个问题:
I'm trying to iterate through nested loops, much like this question:
不过,我需要更深入地研究.那里的评论(日期为 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).
推荐答案
如果你不需要 root dict 中的 name
和 prefix
,你可以将原始列表缩减为简单的区域列表:
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 – 仍然不支持嵌套子元素.
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 嵌套级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!