【问题标题】:Patch kubernetes label with "/" character使用“/”字符修补 kubernetes 标签
【发布时间】:2021-04-29 09:49:36
【问题描述】:

我的following code 工作正常。它在 kubernetes 对象中添加标签example: yes

package main

import (
    "fmt"
    "encoding/json"
    "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{})

    for i, pod := range pods.Items {

        payload := []patchStringValue{{
            Op:    "replace",
            Path:  "/metadata/labels/example",
            Value: "yes",
        }}
        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)
        }
    }
}

问题是我需要添加标签example/test,其中包含字符/,我认为这是我的问题的根源。使用 payload 执行之前的代码时:

        payload := []patchStringValue{{
            Op:    "replace",
            Path:  "/metadata/labels/test/example",
            Value: "yes",
        }}

我收到错误:"the server rejected our request due to an error in our request"

我知道另一种方法是使用Update 而不是Patch。但是使用Patch有没有解决这个问题的方法?

【问题讨论】:

    标签: go kubernetes label patch kubernetes-go-client


    【解决方案1】:

    根据JSON补丁使用的JSON pointer notation spec,需要使用~1/进行编码。所以你的有效载荷会变成如下:

            payload := []patchStringValue{{
                Op:    "replace",
                Path:  "/metadata/labels/test~1example",
                Value: "yes",
            }}
    
    # kubectl patch deploy mydeployment --type='json' -p='[{"op": "replace", "path": "/metadata/labels/example~1test", "value":"yes"}]'
    deployment.apps/mydeployment patched
    
    
    # kubectl get deploy mydeployment -o=jsonpath='{@.metadata.labels}'
    map[example/test:yes]
    

    【讨论】:

      猜你喜欢
      • 2021-11-06
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多