What's the shortest way to add a label to a Pod using the Kubernetes go-client
Asked Answered
W

2

4

I have a demo golang program to list Pods without a particular label. I want to modify it so it also can add a label to each pod.

(I'm using the AWS hosted Kubernetes service, EKS so there's some boilerplate code specific to EKS )

package main

import (
    "fmt"
    eksauth "github.com/chankh/eksutil/pkg/auth"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

func main() {
    cfg := &eksauth.ClusterConfig{ClusterName: "my_cluster_name"}

    clientset, _ := eksauth.NewAuthClient(cfg)
    api := clientset.CoreV1()

    // Get all pods from all namespaces without the "sent_alert_emailed" label.
    pods, _ := api.Pods("").List(metav1.ListOptions{LabelSelector: "!sent_alert_emailed"})

    for i, pod := range pods.Items {
        fmt.Println(fmt.Sprintf("[%2d] %s, Phase: %s, Created: %s, HostIP: %s", i, pod.GetName(), string(pod.Status.Phase), pod.GetCreationTimestamp(), string(pod.Status.HostIP)))

        // Here I want to add a label to this pod
        // e.g. something like:
        // pod.addLabel("sent_alert_emailed=true")
    }
}

I know kubectl can be used to add labels, e.g.

kubectl label pod my-pod new-label=awesome                 # Add a Label
kubectl label pod my-pod new-label=awesomer --overwrite    # Change a existing label

I was hoping there would be an equivalent method via the go-client?

Windy answered 1/8, 2019 at 13:44 Comment(0)
W
5

I'm hoping there is a more elegant way, but until I learn about it, I managed to add a label to a Pod using Patch. Here is my demo code (again it has some EKS boilerplate stuff you may be able to ignore):

package main

import (
    "fmt"
    "encoding/json"
    "time"
    "k8s.io/apimachinery/pkg/types"

    eksauth "github.com/chankh/eksutil/pkg/auth"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)

type patchStringValue struct {
    Op    string `json:"op"`
    Path  string `json:"path"`
    Value string `json:"value"`
}

func main() {
    var updateErr error

    cfg := &eksauth.ClusterConfig{ClusterName: "my cluster name"}
    clientset, _ := eksauth.NewAuthClient(cfg)
    api := clientset.CoreV1()

    // Get all pods from all namespaces without the "sent_alert_emailed" label.
    pods, _ := api.Pods("").List(metav1.ListOptions{LabelSelector: "!sent_alert_emailed"})

    for i, pod := range pods.Items {
        fmt.Println(fmt.Sprintf("[%2d] %s, Phase: %s, Created: %s, HostIP: %s", i, pod.GetName(), string(pod.Status.Phase), pod.GetCreationTimestamp(), string(pod.Status.HostIP)))

        payload := []patchStringValue{{
            Op:    "replace",
            Path:  "/metadata/labels/sent_alert_emailed",
            Value: time.Now().Format("2006-01-02_15.04.05"),
        }}
        payloadBytes, _ := json.Marshal(payload)

        _, updateErr = api.Pods(pod.GetNamespace()).Patch(pod.GetName(), types.JSONPatchType, payloadBytes)
        if updateErr == nil {
            fmt.Println(fmt.Sprintf("Pod %s labelled successfully.", pod.GetName()))
        } else {
            fmt.Println(updateErr)
        }
    }
}
Windy answered 1/8, 2019 at 14:23 Comment(0)
J
5

I was trying to add a new label to a node using client-go, based on OP's code snippet, the shortest path that I used is as follow.

labelPatch := fmt.Sprintf(`[{"op":"add","path":"/metadata/labels/%s","value":"%s" }]`, labelkey, labelValue)
_, err = kc.CoreV1().Nodes().Patch(node.Name, types.JSONPatchType, []byte(labelPatch))

Note: add to /metadata/labels will overwrite all existing labels, so I choose the path to /metadata/labels/${LABEL_KEY} to only add the new label

Jere answered 14/10, 2020 at 23:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.