Obtain pod labels of kubernetes deployment

12/17/2020

I'm trying to write code in Go to fetch the labels of the pods created in a deployment. For example:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 80

I know if I use ObjectMeta, I would be able to fetch the metadata of the deployment, but I would not be able to fetch the spec. Is there a way to get the data from the spec level of the resource?

-- Bobby Bob
go
kubernetes
yaml

1 Answer

12/17/2020

Using kubernetes client-go and this example I was able to get the labels for each container

package main

import (
	"context"
	"flag"
	"fmt"
	"log"
	"path/filepath"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
)

func main() {
	var kubeconfig *string
	if home := homedir.HomeDir(); home != "" {
		kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
	} else {
		kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
	}
	flag.Parse()

	// use the current context in kubeconfig
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		log.Fatalf(err.Error())
	}

	// create the clientset
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		log.Fatalf(err.Error())
	}

  // get pods
	pods, err := clientset.CoreV1().Pods("your-namespace").List(context.TODO(), metav1.ListOptions{})
	if err != nil {
		log.Fatalf(err.Error())
	}

  // get labels
  for _, pod := range pods.Items {
    labels := pod.GetObjectMeta().GetLabels()
    fmt.Printf("%+v", labels)
  }
}
-- mathieux51
Source: StackOverflow