如何在 Kubernetes 的 Go 客户端中根据标签列出 Pod?

huangapple go评论83阅读模式
英文:

How to list Pods based on Labels in kubernetes go-client

问题

我已经尝试根据标签列出Pods:

// Kubernetes客户端 - 包kubernetes
clientset := kubernetes.NewForConfigOrDie(config)

// 创建一个临时列表用于存储
var podslice []string

// 获取Pods - 包metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
pods, _ := clientset.CoreV1().Pods("").List(metav1.ListOptions{})
for _, p := range pods.Items {
    fmt.Println(p.GetName())
}

这相当于执行以下命令:

kubectl get po

有没有办法在Golang中执行以下命令:

kubectl get po -l app=foo

提前感谢。

英文:

I have tried to list pods based on labels

	// Kubernetes client - package kubernetes
	clientset := kubernetes.NewForConfigOrDie(config)

    // create a temp list for storage 
    var podslice []string

	// Get pods -- package metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	pods, _ := clientset.CoreV1().Pods("").List(metav1.ListOptions{})
	for _, p := range pods.Items {
		fmt.Println(p.GetName())
	}

this is equivalent of

kubectl get po 

is there a way to get in golang

kubectl get po -l app=foo

thanks in advance

答案1

得分: 6

你可以使用ListOptions参数来设置。

listOptions := metav1.ListOptions{
    LabelSelector: "app=foo",
}
pods, _ := clientset.CoreV1().Pods("").List(listOptions)

如果你有多个标签,你可以使用labels库来执行,代码如下(未经测试):

import "k8s.io/apimachinery/pkg/labels"

labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"app": "foo"}}
listOptions := metav1.ListOptions{
    LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
}
pods, _ := clientset.CoreV1().Pods("").List(listOptions)
英文:

You may just be able to set using the ListOptions parameter.

listOptions := metav1.ListOptions{
        LabelSelector: "app=foo",
    }
pods, _ := clientset.CoreV1().Pods("").List(listOptions)

If you have multiple labels, you may be able to perform this via the labels library, like below untested code:

import "k8s.io/apimachinery/pkg/labels"

labelSelector := metav1.LabelSelector{MatchLabels: map[string]string{"app": "foo"}}
listOptions := metav1.ListOptions{
    LabelSelector: labels.Set(labelSelector.MatchLabels).String(),
}
pods, _ := clientset.CoreV1().Pods("").List(listOptions)

huangapple
  • 本文由 发表于 2022年9月27日 01:13:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/73857627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定