Ansible版本:ansible 2.6.2 python版本2.7.5
我有一个来自 ansible playbook 的调试输出,它提供以下内容:
"msg": {
"changed": false,
"failed": false,
"guest_disk_facts": {
"0": {
"backing_datastore": "datastore1",
"backing_disk_mode": "persistent",
"backing_eagerlyscrub": false,
"backing_filename": "[datastore1] test-1.vmdk",
"backing_thinprovisioned": false,
"backing_uuid": "6000C290-3e84-38aa-4e56-fbaba882190c",
"backing_writethrough": false,
"capacity_in_bytes": 53687091200,
"capacity_in_kb": 52428800,
"controller_key": 1000,
"key": 2000,
"label": "Hard disk 1",
"summary": "52,428,800 KB",
"unit_number": 0
},
"1": {
"backing_datastore": "datastore2",
"backing_disk_mode": "persistent",
"backing_eagerlyscrub": true,
"backing_filename": "[datastore2] test-1.vmdk",
"backing_thinprovisioned": false,
"backing_uuid": "6000C297-5d68-8010-7b09-75cf83e30801",
"backing_writethrough": false,
"capacity_in_bytes": 10737418240,
"capacity_in_kb": 10485760,
"controller_key": 1000,
"key": 2001,
"label": "Hard disk 2",
"summary": "10,485,760 KB",
"unit_number": 1
},
"2": {
"backing_datastore": "datastore5",
"backing_disk_mode": "persistent",
"backing_eagerlyscrub": false,
"backing_filename": "[datastore5] test-1.vmdk",
"backing_thinprovisioned": false,
"backing_uuid": "6000C292-1f84-3549-c198-d660e6955eda",
"backing_writethrough": false,
"capacity_in_bytes": 150323855360,
"capacity_in_kb": 146800640,
"controller_key": 1000,
"key": 2002,
"label": "Hard disk 3",
"summary": "146,800,640 KB",
"unit_number": 2
}
}
}
}
剧本中的示例任务如下,其输出如下:
- name: Debug disk facts
debug: msg={{ output }}
我如何迭代数组以仅打印“备份数据存储”信息,所以我设法将其注册到变量或标准输出中?
我尝试过这样做但失败了。但我需要所有数组的值
debug: msg={{ output.guest_disk_facts.0 }}
fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: dict object has no element 0\n\nThe error appears to have been in ...
答案1
这就是你要找的东西吗?
- debug:
var: item
loop: "{{ output.guest_disk_facts.values()|json_query('[].backing_datastore') }}"
或者
- debug:
var: item
loop: "{{ output.guest_disk_facts|dict2items|json_query('[].value.backing_datastore') }}"
给出(grep item\“:)
"item": "datastore2"
"item": "datastore1"
"item": "datastore5"