Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 770
Pradeep Padmanaban C Avatar asked Oct 27 '25 05:10

Pradeep Padmanaban C


1 Answers

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)
like image 174
Sankar Avatar answered Oct 28 '25 19:10

Sankar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!