Flissek
Flissek

Reputation: 1

Ansible double iteration loop to get arrays

I want to make loop on the loop in ansible to iterate through arrays.

I have two (or multiple) objects situation like this:

foo:
bar:

The items 'foo' and 'bar' are arrays and I want to iterate through each element of those arrays. As an output I want to have items like:

foo[0], foo[1], foo[3], bar[0], bar[1], bar[3]

Lets try to iterate on debug module:

- name: loop in loop
  vars:
    winamp:
      - foo
      - bar
  debug:
    msg: "{{ item }}"
  with_items: "{{ winamp }}"

This will give only result like 'foo' and 'bar' instead of foo[0], foo[1], foo[2], bar[0], bar[1].

How to get double iteration?

Upvotes: 0

Views: 104

Answers (2)

Vladimir Botka
Vladimir Botka

Reputation: 68254

For example,

    - debug:
        var: item
      loop: "{{ winamp.values()|flatten }}"
      vars:
        winamp:
          foo: ['foo[0]', 'foo[1]', 'foo[2]']
          bar: ['bar[0]', 'bar[1]']

gives (abridged)

  item: foo[0]
  item: foo[1]
  item: foo[2]
  item: bar[0]
  item: bar[1]

Upvotes: 1

You can do it like this:

  hosts: localhost
  vars:
    objs:
      foo: ["Foo1", "Foo2", "Foo3"]
      bar: ["Bar1", "Bar2", "Bar3"]
  tasks:
    - debug:
        msg: "Key={{ item.0.key }} value={{ item.1 }}"
      loop: "{{ objs | dict2items | subelements('value') }}"

Upvotes: 1

Related Questions