可以使用with_nested
或with_cartesian
这两个循环控制结构。
with_nested
:用于遍历两个嵌套的列表,并逐个取出其中的元素进行操作。示例代码如下:- name: Example using with_nested
debug:
msg: "Outer item: {{ item.0 }}, Inner item: {{ item.1 }}"
with_nested:
- [1, 2, 3]
- ['a', 'b', 'c']
上述代码会输出如下结果:
TASK [Example using with_nested] *************************************************************************************
ok: [localhost] => (item=[1, 'a']) => {
"msg": "Outer item: 1, Inner item: a"
}
ok: [localhost] => (item=[1, 'b']) => {
"msg": "Outer item: 1, Inner item: b"
}
ok: [localhost] => (item=[1, 'c']) => {
"msg": "Outer item: 1, Inner item: c"
}
ok: [localhost] => (item=[2, 'a']) => {
"msg": "Outer item: 2, Inner item: a"
}
ok: [localhost] => (item=[2, 'b']) => {
"msg": "Outer item: 2, Inner item: b"
}
ok: [localhost] => (item=[2, 'c']) => {
"msg": "Outer item: 2, Inner item: c"
}
ok: [localhost] => (item=[3, 'a']) => {
"msg": "Outer item: 3, Inner item: a"
}
ok: [localhost] => (item=[3, 'b']) => {
"msg": "Outer item: 3, Inner item: b"
}
ok: [localhost] => (item=[3, 'c']) => {
"msg": "Outer item: 3, Inner item: c"
}
with_cartesian
:用于对两个列表进行笛卡尔积操作,生成一个元素为元组的列表。示例代码如下:- name: Example using with_cartesian
debug:
msg: "Combination: {{ item }}"
with_cartesian:
- [1, 2, 3]
- ['a', 'b', 'c']
上述代码会输出如下结果:
TASK [Example using with_cartesian] **********************************************************************************
ok: [localhost] => (item=[1, 'a']) => {
"msg": "Combination: [1, 'a']"
}
ok: [localhost] => (item=[1, 'b']) => {
"msg": "Combination: [1, 'b']"
}
ok: [localhost] => (item=[1, 'c']) => {
"msg": "Combination: [1, 'c']"
}
ok: [localhost] => (item=[2, 'a']) => {
"msg": "Combination: [2, 'a']"
}
ok: [localhost] => (item=[2, 'b']) => {
"msg": "Combination: [2, 'b']"
}
ok: [localhost] => (item=[2, 'c']) => {
"msg": "Combination: [2, 'c']"
}
ok: [localhost] => (item=[3, 'a']) => {
"msg": "Combination: [3, 'a']"
}
ok: [localhost] => (item=[3, 'b']) => {
"msg": "Combination: [3, 'b']"
}
ok: [localhost] => (item=[3, 'c']) => {
"msg": "Combination: [3, 'c']"
}
这些方法可以帮助我们在Ansible中同时遍历两个列表,并进行相关操作。对于更复杂的场景,Ansible还提供了其他循环控制结构和过滤器,可根据具体需求选择适合的方法。
领取专属 10元无门槛券
手把手带您无忧上云