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
~1to encode/. So your payload would become as follows: