Home > Software engineering >  How can I get k8s annotation in a pod by golang?
How can I get k8s annotation in a pod by golang?

Time:09-17

When I'm running a Golang application in a Kubernetes, I want to get the annotations of the pod where it's running.

Is there any library can help me to do that?

CodePudding user response:

You are looking for the library

https://github.com/kubernetes/apimachinery. It has methods like below which can be usefull for your usecase.

func (meta *ObjectMeta) SetAnnotations(annotations map[string]string)
func HasAnnotation(obj ObjectMeta, ann string) bool

Ref:

  1. https://pkg.go.dev/k8s.io/[email protected]/pkg/apis/meta/v1#HasAnnotation
  2. https://pkg.go.dev/k8s.io/[email protected]/pkg/apis/meta/v1#ObjectMeta.SetAnnotations

CodePudding user response:

Assuming you know the name of the pod of which you want to retrieve the annotations, using example pod nginx-6799fc88d8-mzmcj below:

package main

import (
    "context"
    "fmt"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes"
    "k8s.io/client-go/rest"
)

func main() {
    config, _ := rest.InClusterConfig()
    clientset, _ := kubernetes.NewForConfig(config)
    pod, _ := clientset.CoreV1().Pods("default").Get(context.TODO(), "nginx-6799fc88d8-mzmcj", metav1.GetOptions{})
    for annotation_name, annotation_value := range pod.GetAnnotations(){
        fmt.Println(annotation_name, annotation_value)
    }
}

and the result:

$ kubectl logs incluster-app-6dc44ddcf5-dxj8p
cni.projectcalico.org/containerID 7a63f9befd1174d68384adc05735fbcb1482dfe0d312839736531e90fa9fe790
cni.projectcalico.org/podIP 10.0.124.193/32
cni.projectcalico.org/podIPs 10.0.124.193/32
  • Related