如何用jq过滤Juju Status输出,生成特定结构的JSON
用jq过滤Juju Status JSON生成机器-实例ID-单元映射结构
没问题,我之前经常处理Juju的状态数据转换,这个需求用jq完全可以轻松实现。下面是针对性的解决方案,包含命令、解释和示例验证:
核心jq命令
juju status --format json | jq ' # 第一步:构建机器ID到instance-id的映射字典 ( .machines | to_entries | map({key: .key, value: .value."instance-id"}) | from_entries ) as $machine_map # 第二步:遍历所有单元,关联对应的机器信息,构建目标结构 | .units | to_entries | reduce .[] as $unit ({}; .[$unit.value.machine] = { "instance-id": $machine_map[$unit.value.machine], "unit-name": $unit.key } ) # 可选:补充没有绑定单元的机器(将unit-name设为null),不需要的话可以删除这段 | . + ($machine_map | to_entries | map(select(.key | IN(keys[])|not)) | map({key: .key, value: {"instance-id": .value, "unit-name": null}}) | from_entries) '
命令解释
我把命令拆成几个关键部分,方便你理解:
- 机器ID映射构建:
( .machines | to_entries | map({key: .key, value: .value."instance-id"}) | from_entries ) as $machine_map
这段把Juju状态里的machines对象转换成一个键值对字典,键是机器ID,值是对应的instance-id,后续可以快速通过机器ID查找实例ID。 - 单元关联处理:
.units | to_entries | reduce .[] as $unit ({}; ...)
遍历所有单元,用reduce方法逐步构建目标JSON对象:以单元绑定的机器ID为键,存入对应的instance-id(从之前的字典里取)和单元名称(就是单元本身的键,比如easyrsa/0)。 - 可选的无单元机器补充:最后那段代码会把没有绑定任何单元的机器也加入结果,把
unit-name设为null,如果你的场景只需要有单元的机器,直接删掉这段即可。
示例验证
假设你的Juju Status JSON输入是这样的:
{ "machines": { "0": {"instance-id": "i-123456"}, "1": {"instance-id": "i-789012"}, "2": {"instance-id": "i-345678"}, "10": {"instance-id": "i-901234"}, "11": {"instance-id": "i-567890"} }, "units": { "easyrsa/0": {"machine": "0"}, "etcd/0": {"machine": "1"}, "kubeapi-load-balancer/0": {"machine": "2"}, "kubernetes-worker/4": {"machine": "10"} } }
运行命令后会输出你想要的结构:
{ "0": { "instance-id": "i-123456", "unit-name": "easyrsa/0" }, "1": { "instance-id": "i-789012", "unit-name": "etcd/0" }, "2": { "instance-id": "i-345678", "unit-name": "kubeapi-load-balancer/0" }, "10": { "instance-id": "i-901234", "unit-name": "kubernetes-worker/4" }, "11": { "instance-id": "i-567890", "unit-name": null } }
内容的提问来源于stack exchange,提问作者Jim
相关产品推荐
相关产品推荐

