我正在尝试使用循环来检索多个列表嵌套字典中存在的多个值。 不幸的是,除非我明确定义我想要获取哪个列表,否则我似乎无法这样做。 由于我打算定义数百个这样的设备,我希望有一些东西可以更好地扩展。
#playbook.yml
tasks:
- name: Get volume details using name
get_storage_volume:
host: "{{ host }}"
username: "{{ username }}"
password: "{{ password }}"
name: "{{ inventory_hostname }}-{{ item.volsuffix }}"
state: "present"
register: volume_results
loop: "{{ volumes }}"
volumes:
- volsuffix: data1
volsize: 100
mount_path: /data/fs1
fstype: xfs
mount_opts: noatime
storage_protocol: fc
- volsuffix: data2
volsize: 100
mount_path: /data/fs2
fstype: xfs
mount_opts: noatime,_netdev
storage_protocol: iscsi
- debug:
msg: "{{ volume_results.results.0.attrs.serial_number }}"
#msg: "{{ volume_results.results.1.attrs.serial_number }}"
我想避免显式调用列表条目 [0] 和 [1],如下所示:
TASK [debug] *********************************************************************************************************************************************************************************************************************************************************************************************************************
ok: [node1] => {
"msg": "abcdef12345"
}
ok: [node2] => {
"msg": "cvbnm46807"
}
如果我输出所有“{{volume_results.result }}”,数据格式如下:
TASK [debug] *******************************************************************
ok: [node1] => {
"volume_results.results": [
{
"ansible_loop_var": "item",
"attrs": {
"agent_type": "none",
"name": "node1-data1",
"serial_number": "abcdef12345",
"warn_level": 0
},
},
{
"ansible_loop_var": "item",
"attrs": {
"agent_type": "none",
"name": "node1-data2",
"serial_number": "987654qwert",
"warn_level": 0
}
}
]
}
ok: [node2] => {
"volume_results.results": [
{
"ansible_loop_var": "item",
"attrs": {
"agent_type": "none",
"name": "node2-data1",
"serial_number": "cvbnm46807",
"warn_level": 0
},
},
{
"ansible_loop_var": "item",
"attrs": {
"agent_type": "none",
"name": "node2-data2",
"serial_number": "asdfg56789",
"warn_level": 0
}
}
]
}
想法?
要么使用地图,例如,
- debug:
msg: "{{ volume_results.results|
map(attribute='attrs.serial_number') }}"
,或json_query
- debug:
msg: "{{ volume_results.results|
json_query('[].attrs.serial_number') }}"
两个选项给出相同的结果
msg:
- abcdef12345
- 987654qwert