在 Ansible 中迭代两个带有索引的列表

Iterate over two lists with indexes in Ansible

我精通编程语言,但有些东西我无法使用 Ansible 过滤器和 YAML 语法完成。 基本上,我想遍历 array/lists 并对每个元素进行比较,就像 C 语言中的那样:

for (i=0;i<a;i++) {
  for (j=0;j<b;j++) {
     if (array1[i]==array2[j]) {
        ....     
     }
  }
}

在我的例子中,我试图逐一比较两个列表的每个属性。

有没有办法用 Ansible 来做?

提前感谢您的回答。

例如

- hosts: localhost
  vars:
    array1: [a, b, c]
    array2: [b, d, c, a]
  tasks:
    - debug:
        msg: "{{ item.0 }} == {{ item.1 }} {{ item.0 == item.1 }}"
      loop: "{{ array1|product(array2)|list }}"

给予

  msg: a == b False
  msg: a == d False
  msg: a == c False
  msg: a == a True
  msg: b == b True
  msg: b == d False
  msg: b == c False
  msg: b == a False
  msg: c == b False
  msg: c == d False
  msg: c == c True
  msg: c == a False

如果要查找索引

    - debug:
        msg: "array1[{{ array1.index(item.0) }}] ==
              array2[{{ array2.index(item.1) }}]"
      loop: "{{ array1|product(array2)|list }}"
      when: item.0 == item.1

给予

  msg: array1[0] == array2[3]
  msg: array1[1] == array2[0]
  msg: array1[2] == array2[2]