是否可以编写JMESPath表达式来返回设置了特定子属性值的对象名称列表?在下面的示例中,我想获取fileexists.stat.exists设置为 true 的所有主机名的列表。
我的目标是使用 Ansible hostvars 结构来获取存在特定文件的所有主机的列表。
{
"hostvars": {
"oclab1n01.example.org": {
"fileexists": {
"changed": false,
"failed": false,
"stat": {
"exists": false
}
}
},
"oclab1n02.example.org": {
"fileexists": {
"changed": false,
"failed": false,
"stat": {
"exists": true
}
}
},
"oclab1n03.example.org": {
"fileexists": {
"changed": false,
"failed": false,
"stat": {
"exists": true
}
}
}
} }
在这个例子中,我想得到以下输出
["oclab1n02.example.org", "oclab1n03.example.org"]
简答题(TL;博士(
是的,这是可能的,但它非常麻烦,因为至少在使用 JMESpath 方面,源数据集对于这种通用查询的规范化很差。
上下文
- JMePath查询语言
- 查询深度嵌套对象的对象属性
问题
- 如何使用筛选器表达式构造 jmespath 查询
- 目标是筛选具有任意嵌套对象属性的对象
溶液
- 这可以使用 jmespath 完成,但操作会很麻烦
- 一个有问题的问题是:对于这种 jmespath 查询,源数据集的规范化很差
- 为了构造 jmespath 查询,我们必须假设在创建查询之前所有主对象键都是已知的
- 在这个具体的例子中,我们必须知道在构造 jmespath 查询之前有三个而且只有三个主机名......如果我们希望灵活地指定任意数量的主机名,这不是一个有利的情况
例
以下(太大了(jmespath查询...
[
{
"hostname": `oclab1n01.example.org`
,"fileexists_stat_exists": @.hostvars."oclab1n01.example.org".fileexists.stat.exists
}
,{
"hostname": `oclab1n02.example.org`
,"fileexists_stat_exists": @.hostvars."oclab1n02.example.org".fileexists.stat.exists
}
,{
"hostname": `oclab1n03.example.org`
,"fileexists_stat_exists": @.hostvars."oclab1n02.example.org".fileexists.stat.exists
}
]|[? @.fileexists_stat_exists == `true`]|[*].hostname
返回以下所需结果
[
"oclab1n02.example.org",
"oclab1n03.example.org"
]
陷阱
- 此用例的一个主要缺陷是源数据集对此类查询的规范化很差
- 更扁平化的数据结构将更容易查询
- 因此,如果可能的话,更好的方法是在对源数据集运行 jmespath 查询之前将其展平化。
具有不同原始数据集的替代示例
如果原始数据被组织为对象列表,而不是对象中的一组嵌套对象,则搜索、排序和过滤列表会更容易,而不必事先知道涉及多少主机名条目。
{"hostvars": [
{"hostname":"oclab1n01.example.org"
,"fileexists": true
,"filechanged": false
,"filefailed": false
,"filestat_exists": false
,"we_can_even_still_deeply_nest":{"however":
{"im_only_doing":"it here","to":"prove a point"}
}
}
,{"hostname":"oclab1n02.example.org"
,"fileexists": true
,"filechanged": false
,"filefailed": false
,"filestat_exists": true
}
,{"hostname":"oclab1n03.example.org"
,"fileexists": true
,"filechanged": false
,"filefailed": false
,"filestat_exists": true
}
]
}
现在可以轻松查询上述重新规范化的数据集
hostvars|[? @.filestat_exists == `true`]|[*].hostname