简体   繁体   中英

Patch kubernetes label with “/” character

I have the following code that is working fine. It adds the label example: yes in the kubernetes object:

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

The problem is that I need to add the label example/test , that contains the character / , which I think is the origin of my problem. When executing the previous code with the payload:

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

I get the error: "the server rejected our request due to an error in our request" .

I know an alternative way is using Update instead of Patch . But is there any solution of this problem using Patch ?

According to JSON pointer notation spec which JSON patch uses, you need to use ~1 to encode / . So your payload would become as follows:

        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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM