lonix
lonix

Reputation: 20591

Ansible loop over list of dictionaries and individual dictionaries

I want to loop over a list of dictionaries, as well as other dictionaries. They all have the same schema.

  - set_fact:
      my_list:
        - { foo: 1, bar: 2, baz: 3 }
        - { foo: 4, bar: 5, baz: 6 }
        - { foo: 7, bar: 8, baz: 9 }

  - debug:
      msg: "{{item.foo}} {{item.bar}} {{item.baz}}"
    loop:
      - "{{ my_list }}"
      - { foo: 10, bar: 11, baz: 12 }
      - { foo: 13, bar: 14, baz: 15 }

But this gives:

FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'list object' has no attribute 'foo'

How do I do this?

Upvotes: 1

Views: 1624

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68024

Concatenate the lists, e.g.

    - debug:
        msg: "{{ item.foo }} {{ item.bar }} {{ item.baz }}"
      loop: "{{ my_list +
                [{'foo': 10, 'bar': 11, 'baz': 12}] +
                [{'foo': 13, 'bar': 14, 'baz': 15}] }}"

gives

  msg: 1 2 3
  msg: 4 5 6
  msg: 7 8 9
  msg: 10 11 12
  msg: 13 14 15

The YAML format below gives the same result

    - debug:
        msg: "{{ item.foo }} {{ item.bar }} {{ item.baz }}"
      loop: "{{ my_list + _list2 + _list3 }}"
      vars:
        _list2:
          - foo: 10
            bar: 11
            baz: 12
        _list3:
          - foo: 13
            bar: 14
            baz: 15

Upvotes: 1

Related Questions