I'm currently writing a validating webhook for Kubernetes. I'm facing a problem trying to deserialize a admission request coming from the Kubernetes API into a Kubernetes Object. The resource could be any of: pods, deployments, statefulsets, ingresses, services. The universalDeserializer asks me the type, but I can't know the type with the AdmissionRequest. There's any Decoder that takes just the Raw object and decodes it in a valid object?
I've tried to deserialize an AdmissionRequest.Request.Object.Raw and received that error:
panic: Object 'Kind' is missing in '{"metadata":{"name":"gac","namespace":"all","uid":"2b38b994-9cf4-11e9-bb40-0800270c8766","generation":1,"creationTimestamp":"2019-07-02T18:06:52Z","labels":{"app":"gac","release":"nao_pode_essa"}},"spec":{"replicas":1,"selector":{"matchLabels":{"app":"gac","release":"2"}},"template":{"metadata":{"creationTimestamp":null,"labels":{"app":"gac","release":"2"}},"spec":{"containers":'...
But there was Kind in my object.
I've tried to deserialize this using the JSON representation of the object and it worked.
This is my code:
func main() {
review := v1beta1.AdmissionReview{}
body := `{"kind":"AdmissionReview","apiVersion":"admission.k8s.io/v1beta1","request":{"uid":"2b38c0e2-9cf4-11e9-bb40-0800270c8766","kind":{"group":"apps","version":"v1","kind":"Deployment"},"resource":{"group":"apps","version":"v1","resource":"deployments"},"namespace":"all","operation":"CREATE","userInfo":{"username":"minikube-user","groups":["system:masters","system:authenticated"]},"object":{"metadata":{"name":"gac","namespace":"all","uid":"2b38b994-9cf4-11e9-bb40-0800270c8766","generation":1,"creationTimestamp":"2019-07-02T18:06:52Z","labels":{"app":"gac","release":"nao_pode_essa"}},"spec":{"replicas":1,"selector":{"matchLabels":{"app":"gac","release":"2"}},"template":{"metadata":{"creationTimestamp":null,"labels":{"app":"gac","release":"2"}},"spec":{"containers":[{"name":"erickkkkk","image":"erickfaustino/gac:v0.1.0","ports":[{"name":"http","containerPort":8443,"protocol":"TCP"}],"resources":{"limits":{"cpu":"1","memory":"1Gi"},"requests":{"cpu":"200m","memory":"200Mi"}},"terminationMessagePath":"/dev/termination-log","terminationMessagePolicy":"File","imagePullPolicy":"Always"}],"restartPolicy":"Always","terminationGracePeriodSeconds":30,"dnsPolicy":"ClusterFirst","securityContext":{},"schedulerName":"default-scheduler"}},"strategy":{"type":"RollingUpdate","rollingUpdate":{"maxUnavailable":"25%","maxSurge":"25%"}},"revisionHistoryLimit":10,"progressDeadlineSeconds":600},"status":{}},"oldObject":null,"dryRun":false}}`
bbyte := []byte(body)
ud := scheme.Codecs.UniversalDeserializer()
_, _, err := ud.Decode(bbyte, nil, &review)
if err != nil {
panic(err)
}
raw := review.Request.Object.Raw
lero, _, err := ud.Decode(raw, nil, nil)
if err != nil {
panic(err)
}
fmt.Println(lero)
}