Ansible with_subelements nested levels

2019-03-01 23:25发布

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

Ansible with_subelements

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?

My data:

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

My task:

- 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).

1条回答
该账号已被封号
2楼-- · 2019-03-02 00:15

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

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.

查看更多
登录 后发表回答