pca*_*ana 6 label patch go kubernetes kubernetes-go-client
我有以下运行良好的代码。example: yes它在 kubernetes 对象中添加标签:
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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题是我需要添加example/test包含字符的标签,/我认为这是问题的根源。当使用有效负载执行前面的代码时:
payload := []patchStringValue{{
Op: "replace",
Path: "/metadata/labels/test/example",
Value: "yes",
}}
Run Code Online (Sandbox Code Playgroud)
我收到错误:"the server rejected our request due to an error in our request"。
我知道另一种方法是使用Update而不是Patch. 但是这个问题有什么解决办法吗Patch?
根据JSON 补丁使用的 JSON 指针表示法规范,您需要使用~1来编码/. 所以你的有效负载将变成如下:
payload := []patchStringValue{{
Op: "replace",
Path: "/metadata/labels/test~1example",
Value: "yes",
}}
Run Code Online (Sandbox Code Playgroud)
# 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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1791 次 |
| 最近记录: |