我有以下令人毛骨悚然的事实,
"facter_partitions": {
"/dev/loop0": {
"backing_file": "/a",
"size": "10.92 GiB",
"size_bytes": 3080000000
},
"/dev/loop1": {
"backing_file": "/b",
"size": "11.92 GiB",
"size_bytes": 1080000000
},
"/dev/loop10": {
"backing_file": "/c",
"size": "12.02 GiB",
"size_bytes": 2064000000
}
},
我们如何在剧本中动态获取键和值对。可能正在使用for循环。
这是字典。您必须使用将其转换为列表dict2items
,然后才能访问每个项目的键值对,如下所示:
---
- hosts: localhost
gather_facts: false
vars:
"facter_partitions": {
"/dev/loop0": {
"backing_file": "/a",
"size": "10.92 GiB",
"size_bytes": 3080000000
},
"/dev/loop1": {
"backing_file": "/b",
"size": "11.92 GiB",
"size_bytes": 1080000000
},
"/dev/loop10": {
"backing_file": "/c",
"size": "12.02 GiB",
"size_bytes": 2064000000
}
}
tasks:
- debug: msg="{{ item.key }} - {{ item.value.backing_file }}"
loop: "{{ facter_partitions | dict2items }}"
这将产生类似的输出,
TASK [debug] *******************************************************************
ok: [127.0.0.1] => (item={'key': u'/dev/loop10', 'value': {u'size_bytes': 2064000000, u'backing_file': u'/c', u'size': u'12.02 GiB'}}) => {
"msg": "/dev/loop10 - /c"
}
ok: [127.0.0.1] => (item={'key': u'/dev/loop1', 'value': {u'size_bytes': 1080000000, u'backing_file': u'/b', u'size': u'11.92 GiB'}}) => {
"msg": "/dev/loop1 - /b"
}
ok: [127.0.0.1] => (item={'key': u'/dev/loop0', 'value': {u'size_bytes': 3080000000, u'backing_file': u'/a', u'size': u'10.92 GiB'}}) => {
"msg": "/dev/loop0 - /a"
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句