如何使用Kubernetes的fieldSelector查询ownerReferences

15

Kubernetes的GET API是否支持使用fieldSelector参数来查询数组字段的值?

例如,我有一个Pod如下:

apiGroup: v1
kind: Pod
metadata:
  ownerReferences:
  - apiVersion: apps/v1
    blockOwnerDeletion: true
    controller: true
    kind: ReplicaSet
    name: grpc-ping-r7f8r-deployment-54d688d777
    uid: 262bab1a-1c79-11ea-8e23-42010a800016

我可以做类似这样的事情吗:

kubectl get pods --field-selector 'metadata.ownerReferences.uid=262bab1a-1c79-11ea-8e23-42010a800016'

这个命令失败了 (field label not supported: metadata.ownerReferences.uid)。我怀疑原因是ownerReferences本身是一个数组字段。我也尝试过以下方式,但没有成功:

  • metadata.ownerReferences[*].uid=
  • metadata.ownerReferences[].uid=

我可能会尝试使用 Kubernetes API 的 client-go SDK ,但我怀疑由于同样的原因它也不会起作用。

有没有一种服务器端的方法来查询此内容呢?非常感谢。

2个回答

32

--field-selector 只能用于一些有限的字段。

其中包括:

"metadata.name",
"metadata.namespace",
"spec.nodeName",
"spec.restartPolicy",
"spec.schedulerName",
"spec.serviceAccountName",
"status.phase",
"status.podIP",
"status.podIPs",
"status.nominatedNodeName"

但是您可以使用 jq 执行该任务。以下是我用于列出所有已准备好节点的命令。它演示了您要查找的数组字段的使用。

$ kubectl get nodes -o json | jq -r '.items[] | select(.status.conditions[] | select(.type=="Ready" and .status=="True")) | .metadata.name '

master-0
node-1
node-3

谢谢,我找不到哪些字段可以通过字段选择器进行搜索。https://kubernetes.io/docs/concepts/overview/working-with-objects/field-selectors/文档中没有提到。看起来我想做的事情是不可能的。 - ahmet alp balkan
@AhmetB-Google 欢迎随时光临,虽然我知道你不需要这个 :P 但可能会帮助其他人。 - Kamol Hasan
主要区别在于:字段选择器在服务器端起作用。而像jq/yq/jsonpath或客户端go索引工具则在客户端起作用。客户端的缺点是所有对象都需要通过网络传输。有时这并不明显,但有时候却很明显。 - undefined

2
我认为你真正想要做的是过滤而不是查询。通过使用JSONPath,你可以使用?()来过滤内容。
例如,以下方式可以实现:
kubectl get pods -o jsonpath='{range .items[?(.metadata.ownerReferences.uid=262bab1a-1c79-11ea-8e23-42010a800016)]}{.metadata.name}{end}'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接