Patch kubernetes label with "/" character
Asked Answered
O

1

6

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?

Odell answered 25/1, 2021 at 15:5 Comment(0)
F
9

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]
Former answered 25/1, 2021 at 17:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.