10

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.

1 Answer 1

11

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  
2
  • Thanks so much. I couldn't find that documented anywhere online.
    – Travis
    Mar 29, 2019 at 12:20
  • Thank you much for the answering. In the meantime, I have the challenge which I would like to use loop: or with_*: for multiple lists of data: let say input is [1,2], [3,4], [5,6], [7.8] then want to get the return of [[1,3,5,7],[2,4,6,8]] by alternating. What would be better filter for that?
    – spark
    May 6, 2022 at 14:56

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.