Skip to content

Commit

Permalink
📖 update webhooks for core types to match controller-runtime v0.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 Jul 15, 2023
1 parent 5356022 commit 09e5373
Showing 1 changed file with 26 additions and 32 deletions.
58 changes: 26 additions & 32 deletions docs/book/src/reference/webhook-for-core-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,59 +7,53 @@ There is an [example](https://github.com/kubernetes-sigs/controller-runtime/tree
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.
follow the steps below to add admission webhooks for core types. The example shows
how to set up a mutating webhook following the controller-runtime's webhook builder.

## 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.CustomDefaulter](https://pkg.go.dev/sigs.k8s.io/controller-runtime/pkg/webhook/admission?tab=doc#CustomDefaulter)
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 {
log := logf.FromContext(ctx)
pod, ok := obj.(*corev1.Pod)
if !ok {
return fmt.Errorf("expected a Pod but got a %T", obj)
}

// mutate the fields in pod
if pod.Annotations == nil {
pod.Annotations = map[string]string{}
}
pod.Annotations["example-mutating-admission-webhook"] = "foo"

marshaledPod, err := json.Marshal(pod)
if err != nil {
return admission.Errored(http.StatusInternalServerError, err)
}
return admission.PatchResponseFromRaw(req.Object.Raw, marshaledPod)
}
```

If you need a client, just pass in the client at struct construction time.

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
}
```

**Note**: in order to have controller-gen generate the webhook configuration for
you, you need to add markers. For example,
`// +kubebuilder:webhook:path=/mutate-v1-pod,mutating=true,failurePolicy=fail,groups="",resources=pods,verbs=create;update,versions=v1,name=mpod.kb.io`
`// +kubebuilder:webhook:path=/mutate--v1-pod,mutating=true,failurePolicy=fail,groups="",resources=pods,verbs=create;update,versions=v1,name=mpod.kb.io`

## Update main.go

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 All @@ -73,4 +67,4 @@ Deploying it is just like deploying a webhook server for CRD. You need to
You can follow the [tutorial](/cronjob-tutorial/running.md).


[cronjob-tutorial]: /cronjob-tutorial/cronjob-tutorial.md
[cronjob-tutorial]: /cronjob-tutorial/cronjob-tutorial.md

0 comments on commit 09e5373

Please sign in to comment.