pkaramol
pkaramol

Reputation: 19452

Ansible: use both lists and their contents as variable values

I have key - value pairs association in the form of:

- mykey1:
    myvalues1: ['a', 'b', 'c']
- mykey2:
    myvalues2: ['d', 'e']
- mykey3:
    myvalues3: ['f']

I know that using the with_dict construct I can iterate over both keys and values (which are lists). My question is how can I have a loop that iterates over the list's (values) elements?

The output i would like to be able to achieve is:

a', 'b', 'c', 'd', 'e', 'f'

The problem is that I need to maintain the above associations. Is there a way to avoid duplicating list declarations?

Upvotes: 0

Views: 236

Answers (2)

pkaramol
pkaramol

Reputation: 19452

Here is the construct I came up with:

associations:    
    - { key: mykey1, myvalues: ['a', 'b', 'c', ] }
    - { key: mykey2, myvalues: ['d', 'e'] }
    - { key: mykey3, myvalues: ['f'] }

When someone wants to iterate over values as single values

- name: List single items
  debug:
     msg: "{{ item.1 }}"
   with_subelements:
     - associations
     - myvalues

When someone wants to iterate over values as lists

- name: List lists (no pun intended)
  debug:
    msg: "{{ item.myvalues }}"
  with_items: associations

Upvotes: 0

iptizer
iptizer

Reputation: 1218

I'm not quite sure if it is possible with dynamic keys. But assuming the following vars file without the 1,2 and 3:

rootitem:
  - mykey:
      myvalues: ['a', 'b', 'c']
  - mykey:
      myvalues: ['d', 'e']
  - mykey:
      myvalues: ['f']

It is possible using "with_subelements" with the following example:

- name: iterate over list
  debug:
    msg: "the current item is{{ item.0 }} and all subitems are {{ item.1 }}"
  with_subelements:
    - "{{ rootitem }}"
    - mykey.myvalues

This results in 6 iterations one for each of "a,b,c,d,e,f".

Upvotes: 1

Related Questions