Getting all Kubernetes pods that start with a prefix

8/8/2021

I have a Kubernetes cluster with several (unknown number, as more can be created at run time) pods with have a label prefix of x=y. Based on this prefix (x=), how can I programmatically get a list of all the y values?

-- Barak Sason Rofman
go
kubernetes
kubernetes-pod

2 Answers

8/8/2021

You need to do something like bellow:

# 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)
-- Kamol Hasan
Source: StackOverflow

8/9/2021

Use kubernetes client coreV1Api to list the pods matching the labels.

coreV1Api.list_namespaced_pod(namespace=<namespace>, label_selector="X=Y")
-- PGS
Source: StackOverflow