在剧本中动态获取可解释的事实



我有下面这样的可靠事实,

"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"
}

最新更新