Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over two lists in ansible

Tags:

ansible

I'm new at Ansible and YAML syntax and I'm facing a simple issue: how to iterate over two lists, with the same index?

Something like that:

int[] listOne;
int[] listTwo;

---  Attribute some values to the lists  ----

for(int i = 0; i < 10; i++){
  int result = listOne[i] + listTwo[i];
}

In my case, I'm trying to attribute some values to route53 module, and they are in different lists.

Is there anyway to do it? I just found loops that iterate over a single list or nested lists.

like image 589
kamiha Avatar asked Sep 25 '17 17:09

kamiha


2 Answers

UPDATE: Use loop command

[DEPRECATED]

Making a better search in Ansible's documentation, I found with_together module (see in docs), that does exactly what I was looking for.

It's important to look carefully at documentation :)

like image 127
kamiha Avatar answered Nov 14 '22 15:11

kamiha


You can do that with loop and the zip filter:

- name: Loop over two lists
  vars:
    list_one: [1, 2, 3]
    list_two: [one, two, three]
  ansible.builtin.debug:
    msg: "{{ item.0 }} - {{ item.1 }}"
  loop: "{{ list_one | zip(list_two) | list }}"

Output:

TASK [Loop over two lists] ***************************************************
ok: [192.168.0.1] => (item=[1, 'one']) => {
    "msg": "1 - one"
}
ok: [192.168.0.1] => (item=[2, 'two']) => {
    "msg": "2 - two"
}
ok: [192.168.0.1] => (item=[3, 'three']) => {
    "msg": "3 - three"
}

For more than 2 lists, just pass them to the zip filter, too:

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

If you want to combine the lists as a cartesian product, just replace zip by product:

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

For the example from above, the output would then be:

TASK [Loop over two lists] ************************
ok: [192.168.0.1] => (item=[1, 'one']) => {
    "msg": "1 - one"
}
ok: [192.168.0.1] => (item=[1, 'two']) => {
    "msg": "1 - two"
}
ok: [192.168.0.1] => (item=[1, 'three']) => {
    "msg": "1 - three"
}
ok: [192.168.0.1] => (item=[2, 'one']) => {
    "msg": "2 - one"
}
ok: [192.168.0.1] => (item=[2, 'two']) => {
    "msg": "2 - two"
}
ok: [192.168.0.1] => (item=[2, 'three']) => {
    "msg": "2 - three"
}
ok: [192.168.0.1] => (item=[3, 'one']) => {
    "msg": "3 - one"
}
ok: [192.168.0.1] => (item=[3, 'two']) => {
    "msg": "3 - two"
}
ok: [192.168.0.1] => (item=[3, 'three']) => {
    "msg": "3 - three"
}
like image 1
stackprotector Avatar answered Nov 14 '22 14:11

stackprotector