【发布时间】:2021-10-12 10:58:51
【问题描述】:
我有一个 Kubernetes 集群,其中包含多个标签前缀为 x=y 的 Pod(未知数量,因为可以在运行时创建更多)。基于此前缀 (x=),如何以编程方式获取所有 y 值的列表?
【问题讨论】:
-
到目前为止你有什么尝试?
标签: go kubernetes kubernetes-pod
我有一个 Kubernetes 集群,其中包含多个标签前缀为 x=y 的 Pod(未知数量,因为可以在运行时创建更多)。基于此前缀 (x=),如何以编程方式获取所有 y 值的列表?
【问题讨论】:
标签: go kubernetes kubernetes-pod
您需要执行以下操作:
# kClient ---> Kubernetes Client
# List all the pods from all namespaces
podList, err := es.kClient.CoreV1().Pods(core.NamespaceAll).List(context.TODO(), metav1.ListOptions{})
if err != nil {
log.Fatal(err)
}
# Store answer in Ys
var Ys []string
# Loop over all the pods, and check for the label key "x"
# If "x" exists, store the value of "y" in Ys.
for _, pod := range podList.Items {
if y, exists := pod.Labels["x"]; exists {
Ys = append(Ys, y)
}
}
fmt.Println(Ys)
【讨论】:
使用 kubernetes 客户端 coreV1Api 列出与标签匹配的 pod。
coreV1Api.list_namespaced_pod(namespace=<namespace>, label_selector="X=Y")
【讨论】: