Home > Net >  Setting annotations to a pod using SetAnnotations Kubernetes API
Setting annotations to a pod using SetAnnotations Kubernetes API

Time:01-07

I am trying to add a new key value pair to existing set of Annotations to a running Pod using the below example code:

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

const ( 
        configPath = "/home/test/.kube/config"
)
func main() {
        client, _ := connect()
        pod, _ := client.CoreV1().Pods("default").Get(context.TODO(), "nginx-pod",metav1.GetOptions{})
        fmt.Println(pod.Name)
        annotations := map[string]string{
                "foo":"bar",
        }
        pod.SetAnnotations(annotations)
        for name, value := range pod.GetAnnotations() {
                fmt.Println("name := ", name, "value =", value)
        }

}

func connect() (*kubernetes.Clientset, error) {
        restconfig, err := clientcmd.BuildConfigFromFlags("", configPath)
        if err != nil {
                klog.Exit(err.Error())
        }
        clientset, err := kubernetes.NewForConfig(restconfig)
        if err != nil {
                klog.Exit(err.Error())
        }
       return clientset, nil
}

when i run the above code and use "oc describe pods/nginx-pod i don't see the annotation "foo: bar" under the annotations. What's the right way to add New Annotations to an existing pod.

CodePudding user response:

You're going to want something along the lines:

...
pod.SetAnnotations(annotations)
client.
  CoreV1().
  Pods("default").
  Update(context.TODO(), pod, metav1.UpdateOptions{})

See: PodInterface

  •  Tags:  
  • Related