簡體   English   中英

使用 Kubernetes go-client 向 Pod 添加標簽的最短方法是什么

[英]What's the shortest way to add a label to a Pod using the Kubernetes go-client

我有一個演示 golang 程序來列出沒有特定標簽的 Pod。 我想修改它,以便它還可以為每個 pod 添加一個標簽。

(我使用的是 AWS 托管的 Kubernetes 服務 EKS,所以有一些特定於 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")
    }
}

我知道 kubectl 可用於添加標簽,例如

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

我希望通過 go-client 有一個等效的方法?

我希望有一種更優雅的方式,但在我了解它之前,我設法使用Patch將標簽添加到 Pod。 這是我的演示代碼(同樣有一些 EKS 樣板內容,您可以忽略):

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)
        }
    }
}

我試圖根據OP 的代碼片段使用 client-go 向節點添加新標簽,我使用的最短路徑如下。

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

注意: add/metadata/labels覆蓋所有現有標簽,因此我選擇/metadata/labels/${LABEL_KEY}的路徑僅添加新標簽

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM