使用Kubernetes go-client向Pod添加标签的最短方法是什么 [英] What's the shortest way to add a label to a Pod using the Kubernetes go-client

查看:309
本文介绍了使用Kubernetes go-client向Pod添加标签的最短方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个演示golang程序,用于列出没有特定标签的Pod.我想对其进行修改,以便它还可以为每个吊舱添加标签.

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.

(我正在使用AWS托管的Kubernetes服务,EKS,因此有一些特定于EKS的样板代码)

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

我知道kubectl可用于添加标签,例如

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

我希望通过go-client有一种等效的方法吗?

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

推荐答案

我试图基于

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

注意:add/metadata/labels覆盖所有现有标签,因此我选择/metadata/labels/${LABEL_KEY}的路径以仅添加新标签

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

这篇关于使用Kubernetes go-client向Pod添加标签的最短方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆