我试图循环遍历哈希和与之关联的数组,如下所示:
VAR:
dictionary:
aword: [ ant, den ]
bword: [ fat, slim ]
任务:
name: Create symlinks
command: do something with item[0] over item[1]
with_nested:
- "{{ item.key }}"
- "{{ item.value }}"
with_dict: dictionary
这不起作用。我做错了什么或者Ansible不支持这样的迭代吗?
答案 0 :(得分:6)
我使用
解决了这个问题with_subelements
像这样
乏:
dictionary:
- name: aword
words:
- ant
- den
- name: bword
words:
- fat
- slim
任务:
name: Create symlinks
command: do something with item.0.name over item.1
with_subelements:
- dictionary
- words
答案 1 :(得分:1)
为了完整性,也可以使用with_nested
通过在Ansible中创建嵌套列表来完成。这样做可以实现相同的循环行为,而无需设置var / fact。当您要实例化任务本身上的嵌套列表时,这很有用。
像这样:
---
- hosts: localhost
connection: local
become: false
tasks:
- debug:
msg: "do something with {{ item[0] }} over {{ item[1] }}"
with_nested:
- - ant # note the two hyphens to create a list of lists
- den
- - fat
- slim
输出:
TASK [debug] ********************************************************************************************
ok: [localhost] => (item=[u'ant', u'fat']) => {
"changed": false,
"item": [
"ant",
"fat"
],
"msg": "do something with ant over fat"
}
ok: [localhost] => (item=[u'ant', u'slim']) => {
"changed": false,
"item": [
"ant",
"slim"
],
"msg": "do something with ant over slim"
}
ok: [localhost] => (item=[u'den', u'fat']) => {
"changed": false,
"item": [
"den",
"fat"
],
"msg": "do something with den over fat"
}
ok: [localhost] => (item=[u'den', u'slim']) => {
"changed": false,
"item": [
"den",
"slim"
],
"msg": "do something with den over slim"
}