Skip to content

Commit

Permalink
Update README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
snorwin committed Aug 15, 2021
1 parent 2a749e7 commit 953af98
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,51 @@
[![Coverage Status](https://coveralls.io/repos/github/snorwin/k8s-generic-webhook/badge.svg?branch=main)](https://coveralls.io/github/snorwin/k8s-generic-webhook?branch=main)
[![Releases](https://img.shields.io/github/v/release/snorwin/k8s-generic-webhook)](https://github.com/snorwin/k8s-generic-webhook/releases)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)

The **k8s-generic-webhook** is a library to simplify the implementation of webhooks for arbitrary customer resources (CR) in the [operator-sdk](https://sdk.operatorframework.io/) or [controller-runtime](https://github.com/kubernetes-sigs/controller-runtime).
Furthermore, it provides full access to the `AdmissionReview` request and decodes the `Object` in the request automatically. More sophistic webhook logic is facilitated by using the injected `Client` of the webhook which provides full access to the Kubernetes API.

## Quickstart
1. Initialize a new manager using the [operator-sdk](https://sdk.operatorframework.io/).
2. Create a pkg (e.g. `webhooks/pod`) and implement your webhook logic by embedding either the `ValidatingWebhook` or the `MuatatingWebhook`.

```go
package pod

import (
"context"

"github.com/snorwin/k8s-generic-webhook/pkg/webhook"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"
)

type Webhook struct {
webhook.ValidatingWebhook
}

func (w *Webhook) SetupWebhookWithManager(mgr manager.Manager) error {
return webhook.NewGenericWebhookManagedBy(mgr).
For(&corev1.Pod{}).
Complete(w)
}

func (w *Webhook) ValidateCreate(ctx context.Context, req admission.Request) admission.Response {
_ = log.FromContext(ctx)

pod := req.Object.Object.(*corev1.Pod)
// TODO add your programmatic validation logic here

return admission.Allowed("")
}
```

3. Add the following snippet to `main()` in `main.go` in order to register the webhook in the manager.
```go
if err = (&pod.Webhook{}).SetupWebhookWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create webhook", "webhook", "Pod")
os.Exit(1)
}
```

0 comments on commit 953af98

Please sign in to comment.