我有一个JSON对象,其中相关部分的形式为
{
"_meta": {
"hostvars": {
"name_1": {
"ansible_host": "10.0.0.1"
},
"name_2": {
"ansible_host": "10.0.0.2"
},
"name_3": {
"ansible_host": "10.0.0.3"
}
}
},
...
"nodes": {
"hosts": [
"name_1",
"name_2"
]
}
}
(ansible-inventory --list
的输出,供参考(。
我想使用jq
通过在._meta.hostvars
中查找名称来生成nodes
主机的IP列表。在该示例中,输出应该是:
10.0.0.1
10.0.0.2
注意,不应包括10.0.0.3
,因为name_3
不在.nodes.hosts
列表中。所以仅仅做jq -r '._meta.hostvars[].ansible_host'
是行不通的。
我尝试过jq '.nodes.hosts[] | ._meta.hostvars[.].ansible_host'
,但失败了,因为._meta
不会从管道之后的根进行扫描。
您可以在更改上下文之前将根存储在变量中:
jq -r '. as $root | .nodes.hosts[] | $root._meta.hostvars[.].ansible_host'
但一个更好的解决方案是只内联";主机";查询:
jq -r '._meta.hostvars[.nodes.hosts[]].ansible_host'