【问题标题】:What's the shortest way to add a label to a Pod using the Kubernetes go-client使用 Kubernetes go-client 向 Pod 添加标签的最短方法是什么
【发布时间】:2019-12-10 03:17:51
【问题描述】:

我有一个演示 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 有一个等效的方法?

【问题讨论】:

    标签: go kubernetes kubernetes-go-client


    【解决方案1】:

    我希望有一种更优雅的方式,但在我了解它之前,我设法使用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)
            }
        }
    }
    

    【讨论】:

      【解决方案2】:

      我正在尝试使用 client-go 为节点添加新标签,基于 OP's code snippet,我使用的最短路径如下。

      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} 的路径只添加新标签

      【讨论】:

        猜你喜欢
        • 2022-09-27
        • 2020-09-30
        • 1970-01-01
        • 2016-01-04
        • 1970-01-01
        • 2014-09-10
        • 2019-04-11
        • 2019-05-20
        • 2021-09-27
        相关资源
        最近更新 更多