package main
import (
"encoding/json"
"fmt"
jsonpatch "github.com/evanphx/json-patch"
corev1 "k8s.io/api/core/v1"
)
func main() {
var pod = corev1.Pod{
Spec: corev1.PodSpec{
Volumes: []corev1.Volume{
{
Name: "default-token-lsh6v",
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: "default-token-lsh6v",
},
},
},
},
},
}
podBytes, _ := json.Marshal(&pod)
fmt.Printf("old document: %s\n", podBytes)
// {"op": "add", "path": "/spec/dnsConfig/options", "value": [{"name":"single-request-reopen"}]}
patchJSON := []byte(`[
{"op": "add", "path": "/spec", "value": {"dnsConfig": {"options":[{"name":"single-request-reopen"}] }} },
{"op": "add", "path": "/spec/volumes/0", "value":
{
"name":"default-token-lsh6v1111",
"secret":{
"secretName":"default-token-lsh6v1111"
}
}
}
]`)
patch, err := jsonpatch.DecodePatch(patchJSON)
if err != nil {
panic(err)
}
modified, err := patch.Apply(podBytes)
if err != nil {
panic(err)
}
fmt.Printf("Modified document: %s\n", modified)
}
old document: {"metadata":{"creationTimestamp":null},"spec":{"volumes":[{"name":"default-token-lsh6v","secret":{"secretName":"default-token-lsh6v"}}],"containers":null},"status":{}}
panic: add operation does not apply: doc is missing path: "/spec/volumes/0": missing value
use the latest code, seemd ok
how to append a value , not override