Skip to content

Commit

Permalink
📖 update webhooks for core types to match cr 0.15
Browse files Browse the repository at this point in the history
Signed-off-by: Mikko Ylinen <mikko.ylinen@intel.com>
  • Loading branch information
mythi committed May 9, 2023
1 parent 6c11f05 commit f25dbe3
Showing 1 changed file with 20 additions and 28 deletions.
48 changes: 20 additions & 28 deletions docs/book/src/reference/webhook-for-core-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,43 +9,29 @@ in controller-runtime.
It is suggested to use kubebuilder to initialize a project, and then you can
follow the steps below to add admission webhooks for core types.

## Implement Your Handler
## Implement Your Webhook

You need to have your handler implements the
[admission.Handler](https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/webhook/admission?tab=doc#Handler)
You need to have your webhook to implement the
[admission.Defaulter](https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/webhook/admission?tab=doc#Defaulter)
interface.

```go
type podAnnotator struct {
Client client.Client
decoder *admission.Decoder
}
type podAnnotator struct {}

func (a *podAnnotator) Handle(ctx context.Context, req admission.Request) admission.Response {
pod := &corev1.Pod{}
err := a.decoder.Decode(req, pod)
if err != nil {
return admission.Errored(http.StatusBadRequest, err)
}
func (a *podAnnotator) Default(ctx context.Context, obj runtime.Object) error {
var pod *corev1.Pod

// mutate the fields in pod
log := logf.FromContext(ctx)

marshaledPod, err := json.Marshal(pod)
if err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
return admission.PatchResponseFromRaw(req.Object.Raw, marshaledPod)
}
```
d, ok := obj.(*corev1.Pod)
if !ok {
return fmt.Errorf("expected a Pod but got a %T", obj)
}

If you need a client, just pass in the client at struct construction time.
// mutate the fields in pod

If you add the `InjectDecoder` method for your handler, a decoder will be
injected for you.
log.Info("Annotated pod")

```go
func (a *podAnnotator) InjectDecoder(d *admission.Decoder) error {
a.decoder = d
return nil
}
```
Expand All @@ -59,7 +45,13 @@ you, you need to add markers. For example,
Now you need to register your handler in the webhook server.

```go
mgr.GetWebhookServer().Register("/mutate-v1-pod", &webhook.Admission{Handler: &podAnnotator{Client: mgr.GetClient()}})
if err := builder.WebhookManagedBy(mgr).
For(&corev1.Pod{}).
WithDefaulter(&podAnnotator{}).
Complete(); err != nil {
entryLog.Error(err, "unable to create webhook", "webhook", "Pod")
os.Exit(1)
}
```

You need to ensure the path here match the path in the marker.
Expand Down

0 comments on commit f25dbe3

Please sign in to comment.