使用Ansible中的json_query / jmespath过滤器进行多次搜索
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用Ansible中的json_query / jmespath过滤器进行多次搜索相关的知识,希望对你有一定的参考价值。
我正在尝试解析以下json中的特定子网名称,而在json_query中使用contains with或starts_with过滤器。它包含两个vnet,每个vnet都有多个子网:
{
"azure_virtualnetworks": [
{
"name": "test-vnet-172-17-0-0-19",
"properties": {
"subnets": [
{
"name": "test-confluent-subnet-172-17-0-0-28",
"properties": {
"addressPrefix": "172.20.88.0/28",
"networkSecurityGroup": {
"id": "/subscriptions/********/resourceGroups/test-confluent-rg/providers/Microsoft.Network/networkSecurityGroups/test-confluent-nsg"
},
"provisioningState": "Succeeded"
}
},
{
"name": "test-test-subnet-172-17-0-32-28",
"properties": {
"addressPrefix": "172.20.88.32/28",
"networkSecurityGroup": {
"id": "/subscriptions/********/resourceGroups/test-test-rg/providers/Microsoft.Network/networkSecurityGroups/test-test-nsg"
},
"provisioningState": "Succeeded"
}
}
]
}
},
{
"name": "test2-vnet-172-17-1-0-19",
"properties": {
"subnets": [
{
"name": "test-confluent-subnet-172-17-1-0-28",
"properties": {
"addressPrefix": "172.20.88.0/28",
"networkSecurityGroup": {
"id": "/subscriptions/********/resourceGroups/test-confluent-rg/providers/Microsoft.Network/networkSecurityGroups/test-confluent-nsg"
},
"provisioningState": "Succeeded"
}
},
{
"name": "test-qatesting-subnet-172-17-1-16-28",
"properties": {
"addressPrefix": "172.20.88.16/28",
"networkSecurityGroup": {
"id": "/subscriptions/********/resourceGroups/test-qatesting-rg/providers/Microsoft.Network/networkSecurityGroups/test-qatesting-nsg"
},
"provisioningState": "Succeeded"
}
}
]
}
}
]
}
我需要在按虚拟网络名称搜索后搜索子网名称。
我可以毫无问题地过滤到子网列表。例如
azure_virtualnetworks[?contains(name,`test2-vnet`)].properties.subnets[]
收益:
[
{
"name": "test-confluent-subnet-172-17-1-0-28",
"properties": {
"addressPrefix": "172.20.88.0/28",
"networkSecurityGroup": {
"id": "/subscriptions/********/resourceGroups/test-confluent-rg/providers/Microsoft.Network/networkSecurityGroups/test-confluent-nsg"
},
"provisioningState": "Succeeded"
}
},
{
"name": "test-qatesting-subnet-172-17-1-16-28",
"properties": {
"addressPrefix": "172.20.88.16/28",
"networkSecurityGroup": {
"id": "/subscriptions/********/resourceGroups/test-qatesting-rg/providers/Microsoft.Network/networkSecurityGroups/test-qatesting-nsg"
},
"provisioningState": "Succeeded"
}
}
]
但是我在搜索子网时遇到了问题。我曾经认为以下的一些变化可能有效,但没有任何成功:
azure_virtualnetworks[?contains(name,`test2-vnet`)].properties.subnets[?contains(name,`test-confluent`) ]
我正在努力弄清楚纠正语法是什么。
答案
选择所需的子网,使用pipe表达式停止投影,从子网列表中筛选所需的项目:
azure_virtualnetworks[?contains(name,`test2-vnet`)].properties.subnets[] | [?contains(name,`test-confluent`)]
以上是关于使用Ansible中的json_query / jmespath过滤器进行多次搜索的主要内容,如果未能解决你的问题,请参考以下文章