用“/”字符修补 kubernetes 标签

Patch kubernetes label with "/" character

我的 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 是否可以解决这个问题?

根据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]