Last active
April 5, 2021 19:36
-
-
Save developer-guy/c64b62740d06576a368323f425597a92 to your computer and use it in GitHub Desktop.
PodValidator implementation of controller-runtime
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package v1 | |
import ( | |
"context" | |
"fmt" | |
"net/http" | |
corev1 "k8s.io/api/core/v1" | |
"sigs.k8s.io/controller-runtime/pkg/client" | |
"sigs.k8s.io/controller-runtime/pkg/webhook/admission" | |
) | |
// +kubebuilder:webhook:verbs=create;update,path=/validate-core-v1-pod,mutating=false,failurePolicy=fail,groups=core,resources=pods,versions=v1,name=vpod.kb.io | |
// podValidator validates Pods | |
type podValidator struct { | |
Client client.Client | |
decoder *admission.Decoder | |
} | |
func NewPodValidator(c client.Client) admission.Handler { | |
return &podValidator{Client: c} | |
} | |
// podValidator admits a pod if a specific annotation exists. | |
func (v *podValidator) Handle(ctx context.Context, req admission.Request) admission.Response { | |
pod := &corev1.Pod{} | |
err := v.decoder.Decode(req, pod) | |
if err != nil { | |
return admission.Errored(http.StatusBadRequest, err) | |
} | |
key := "example-mutating-admission-webhook" | |
anno, found := pod.Annotations[key] | |
if !found { | |
return admission.Denied(fmt.Sprintf("missing annotation %s", key)) | |
} | |
if anno != "foo" { | |
return admission.Denied(fmt.Sprintf("annotation %s did not have value %q", key, "foo")) | |
} | |
return admission.Allowed("") | |
} | |
// podValidator implements admission.DecoderInjector. | |
// A decoder will be automatically injected. | |
// InjectDecoder injects the decoder. | |
func (v *podValidator) InjectDecoder(d *admission.Decoder) error { | |
v.decoder = d | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment