Travis
Travis

Reputation: 444

Ansible - What's the proper syntax for loop + zip when combining more than two lists?

I haven't been able to find the syntax for loop + zip when combining more than 2 lists.

Since Ansible 2.5, as shown here, the following syntax replaces with_together with loop + zip:

- name: with_together
  debug:
    msg: "{{ item.0 }} - {{ item.1 }}"
  with_together:
    - "{{ list_one }}"
    - "{{ list_two }}"

- name: with_together -> loop
  debug:
    msg: "{{ item.0 }} - {{ item.1 }}"
  loop: "{{ list_one|zip(list_two)|list }}"

My question is, whereas when using with_together, you could simply append lists, and reference them with iterating numbers, I haven't been able to find the method to use with loop + zip. I have tried:

loop: "{{ list_one|zip(list_two)|zip(list_three)|zip(list_four)list }}"

Without success.

Upvotes: 10

Views: 5575

Answers (1)

Nick
Nick

Reputation: 2034

You can append additional arrays inside the zip filter itself.

zip(list, list, list, ...)

For example:

- hosts: localhost
  become: false
  gather_facts: false
  tasks:
  - vars:
      list_one:
      - one
      - two
      list_two:
      - three
      - four
      list_three:
      - five
      - six
    debug:
      msg: "{{ item.0 }} {{ item.1 }} {{ item.2 }}"
    loop: "{{ list_one | zip(list_two, list_three) | list }}"

When run:

PLAY [localhost] *********************************************************************************************************************************************

TASK [debug] *************************************************************************************************************************************************
ok: [localhost] => (item=['one', 'three', 'five']) => {
    "msg": "one three five"
}
ok: [localhost] => (item=['two', 'four', 'six']) => {
    "msg": "two four six"
}

PLAY RECAP ***************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0  

Upvotes: 12

Related Questions