简体   繁体   中英

Ansible Loop within the same loop using with_items

Looking for help trying to loop through multiple pools while some pools may have more than 1 host. I've attempted to do with_nested and with_subelements but both don't seem to do what I want.

- name: Pool members
  bigip_pool_member:
    state: present
    pool: "{{ item.pool }}"
    partition: Common
    host: "{{ item.host }}"
    port: "{{ item.port }}"
    provider:
      server: bigip.domain.com
      user: admin
      password: admin
      validate_certs: no
  delegate_to: localhost
  with_items:
    - { pool: pool, host: [10.10.10.10, 10.10.10.11], port: 80 }
    - { pool: pool2, host: 10.10.10.10, port: 80 }

I believe the host field can only take one value at a time, so I need to loop through the hosts for one pool. The output would be something along the lines of

  bigip_pool_member:
    state: present
    pool: pool
    partition: Common
    host: 10.10.10.10
    port: 80

  bigip_pool_member:
    state: present
    pool: pool
    partition: Common
    host: 10.10.10.11
    port: 80

  bigip_pool_member:
    state: present
    pool: pool2
    partition: Common
    host: 10.10.10.10
    port: 80

Loop subelements is what you're looking for. For example, see the playbook below how to reference the attributes you need

- hosts: localhost
  vars:
    my_pools:
      - {pool: pool, host: [10.10.10.10, 10.10.10.11], port: 80}
      - {pool: pool2, host: [10.10.10.10], port: 80}
  tasks:
    - debug:
        msg: "pool:{{ item.0.pool }} port:{{ item.0.port }} host:{{ item.1 }}"
      with_subelements:
        - "{{ my_pools }}"
        - host

give

    "msg": "pool:pool port:80 host:10.10.10.10"
    "msg": "pool:pool port:80 host:10.10.10.11"
    "msg": "pool:pool2 port:80 host:10.10.10.10"

Notes

  • Simply put the references to the attributes into your code.
  • Be consistent. The attribute host must be a list even if the list has one item only.
  • Use loop instead of with_subelements
      loop: "{{lookup('subelements', my_pools, 'host', {'skip_missing': True})}}"


Below is the task with minimal changes that should make it work

- name: Pool members bigip_pool_member: state: present pool: "{{ item.0.pool }}" partition: Common host: "{{ item.1 }}" port: "{{ item.0.port }}" provider: server: bigip.domain.com user: admin password: admin validate_certs: no delegate_to: localhost with_subelements: - - {pool: pool, host: [10.10.10.10, 10.10.10.11], port: 80} - {pool: pool2, host: [10.10.10.10], port: 80} - host

(not tested)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM