如何解决用“/”字符修补 kubernetes 标签
我的 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 := []patchStringValue{{
Op: "replace",Path: "/metadata/labels/test/example",}}
我收到错误:"the server rejected our request due to an error in our request"
。
我知道另一种方法是使用 Update
而不是 Patch
。但是有没有使用 Patch
解决这个问题的方法?
解决方法
根据JSON patch使用的JSON pointer notation spec,需要使用~1
对/
进行编码。所以你的payload会变成如下:
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]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。