在jq输出中添加一个字段会添加行



我有以下命令:

kubectl get pod -A -o=json | jq -r '[.items[]|select(any( .status.containerStatuses[]; .state.waiting or (.state.terminated and .state.terminated.reason!="Completed")))|{pod:.metadata.name, namespace:.metadata.namespace}]'

这就像我想要的一样工作(除了我需要添加一个字段(。这是结果的摘录:

{
"pod": "ops-test-app-blue-54556c9b8b-pq6hd",
"namespace": "software-operations-test-apps"
},
{
"pod": "ops-test-app-blue-54556c9b8b-vknl8",
"namespace": "software-operations-test-apps"
}

当我添加我需要的额外字段时,它最终看起来像这样:

kubectl get pod -A -o=json | jq -r '[.items[]|select(any( .status.containerStatuses[]; .state.waiting or (.state.terminated and .state.terminated.reason!="Completed")))|{pod:.metadata.name, container:.status.containerStatuses[].name, namespace:.metadata.namespace}]'

这是相同的命令,只是它将容器名称添加到json输出中。然而,当我这样做时,它会添加额外的结果(以及我的额外字段(:

{
"pod": "ops-test-app-blue-54556c9b8b-pq6hd",
"container": "ops-test-app-blue",
"namespace": "software-operations-test-apps"
},
{
"pod": "ops-test-app-blue-54556c9b8b-pq6hd",
"container": "istio-proxy",
"namespace": "software-operations-test-apps"
},
{
"pod": "ops-test-app-blue-54556c9b8b-vknl8",
"container": "ops-test-app-blue",
"namespace": "software-operations-test-apps"
},
{
"pod": "ops-test-app-blue-54556c9b8b-vknl8",
"container": "istio-proxy",
"namespace": "software-operations-test-apps"
}

额外的结果是容器设置为istio-proxy的行。这似乎是因为在.status.containerStatuses的每个实例中都有2个条目。一个用于ops测试应用程序蓝色容器,一个用于istio-proxy应用程序。

但是,当我查看istio-proxy实例的数据时,它与标准不匹配。以下是istio-proxy实例的完整json示例:

{
"containerID": "docker://b99e580b64bb70ba1ddbfc726688e8901d05975c097ec55625cad971994c38a8",
"image": "istio/proxyv2:1.10.0",
"imageID": "docker-pullable://istio/proxyv2@sha256:88c6c693e67a0f2492191a0e7d8020ddc85603bfc704f252655cb9eb5eeb3f58",
"lastState": {},
"name": "istio-proxy",
"ready": true,
"restartCount": 0,
"started": true,
"state": {
"running": {
"startedAt": "2022-01-06T23:52:10Z"
}
}
}

它有一个state.running。(不是select语句用于筛选的state.waitingstate.terminated(。

为什么要添加这些额外的行?

有没有办法得到额外的字段,而不是额外的行

您过滤的东西不对。

.items |
map (
.status.containerStatuses |= map(
select(
(  .state.waiting
or .state.terminated and .state.terminated.reason != "Completed"
)
)
) |
{
pod:       .metadata.name,
namespace: .metadata.namespace,
container: .status.containerStatuses[].name
}
)

最新更新