0

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?

1
  • 1
    Please provide a proper example. Like - foo: [foo0,foo1] and what result do you expect. Commented Sep 27, 2022 at 11:07

2 Answers 2

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') }}"
Sign up to request clarification or add additional context in comments.

Comments

1

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.