@@ -19,53 +19,47 @@ package main
1919import (
2020 "context"
2121 "fmt"
22- "net/http"
2322
2423 corev1 "k8s.io/api/core/v1"
24+ "k8s.io/apimachinery/pkg/runtime"
2525
26- "sigs.k8s.io/controller-runtime/pkg/client"
2726 logf "sigs.k8s.io/controller-runtime/pkg/log"
28- "sigs.k8s.io/controller-runtime/pkg/webhook/admission"
2927)
3028
3129// +kubebuilder:webhook:path=/validate-v1-pod,mutating=false,failurePolicy=fail,groups="",resources=pods,verbs=create;update,versions=v1,name=vpod.kb.io
3230
3331// podValidator validates Pods
34- type podValidator struct {
35- Client client.Client
36- decoder * admission.Decoder
37- }
32+ type podValidator struct {}
3833
39- // podValidator admits a pod if a specific annotation exists.
40- func (v * podValidator ) Handle (ctx context.Context , req admission.Request ) admission.Response {
41- // set up a convenient log object so we don't have to type request over and over again
34+ // validate admits a pod if a specific annotation exists.
35+ func (v * podValidator ) validate (ctx context.Context , obj runtime.Object ) error {
4236 log := logf .FromContext (ctx )
43-
44- pod := & corev1.Pod {}
45- err := v .decoder .Decode (req , pod )
46- if err != nil {
47- return admission .Errored (http .StatusBadRequest , err )
37+ pod , ok := obj .(* corev1.Pod )
38+ if ! ok {
39+ return fmt .Errorf ("expected a Pod but got a %T" , obj )
4840 }
4941
5042 log .Info ("Validating Pod" )
51-
5243 key := "example-mutating-admission-webhook"
5344 anno , found := pod .Annotations [key ]
5445 if ! found {
55- return admission . Denied ( fmt .Sprintf ("missing annotation %s" , key ) )
46+ return fmt .Errorf ("missing annotation %s" , key )
5647 }
5748 if anno != "foo" {
58- return admission . Denied ( fmt .Sprintf ("annotation %s did not have value %q" , key , "foo" ) )
49+ return fmt .Errorf ("annotation %s did not have value %q" , key , "foo" )
5950 }
6051
61- return admission .Allowed ("" )
52+ return nil
53+ }
54+
55+ func (v * podValidator ) ValidateCreate (ctx context.Context , obj runtime.Object ) error {
56+ return v .validate (ctx , obj )
6257}
6358
64- // podValidator implements admission.DecoderInjector.
65- // A decoder will be automatically injected.
59+ func (v * podValidator ) ValidateUpdate (ctx context.Context , oldObj , newObj runtime.Object ) error {
60+ return v .validate (ctx , newObj )
61+ }
6662
67- // InjectDecoder injects the decoder.
68- func (v * podValidator ) InjectDecoder (d * admission.Decoder ) error {
69- v .decoder = d
70- return nil
63+ func (v * podValidator ) ValidateDelete (ctx context.Context , obj runtime.Object ) error {
64+ return v .validate (ctx , obj )
7165}
0 commit comments