Webhook Example

Same as controllers, a Webhook Server is a
Runable which needs to be registered to a manager.
Arbitrary number of Runables can be registered to a manager,
so a webhook server can run with other controllers in the same manager.
They will share the same dependencies provided by the manager. For example, shared cache, client, scheme, etc.

Setup

Way to Deploy your Webhook Server

There are various ways to deploy the webhook server in terms of

Where the serving certificates live.

In what environment the webhook server runs, in a pod or directly on a VM, etc.

If in a pod, on what type of node, worker nodes or master node.

The recommended way to deploy the webhook server is

Run the webhook server as a regular pod on worker nodes through a workload API, e.g. Deployment or StatefulSet.

Put the certificate in a k8s secret in the same namespace as the webhook server

Mount the secret as a volume in the pod

Create a k8s service to front the webhook server.

Creating a Handler

The business logic for a Webhook exists in a Handler.
A Handler implements the admission.Handler interface, which contains a single Handle method.

If a Handler implements inject.Client and inject.Decoder interfaces,
the manager will automatically inject the client and the decoder into the Handler.

Note: The client.Client provided by the manager reads from a cache which is lazily initialized.
To eagerly initialize the cache, perform a read operation with the client before starting the server.

podAnnotator is a Handler, which implements the admission.Handler, inject.Client and inject.Decoder interfaces.

Details about how to implement an admission webhook podAnnotator is covered in a later section.

Creating a Server

A Server registers Webhook Configuration with the apiserver and creates an HTTP server to route requests to the handlers.

The server is behind a Kubernetes Service and provides a certificate to the apiserver when serving requests.

The Server depends on a Kubernetes Secret containing this certificate to be mounted under CertDir.
The Secret needs to present but not have to be prepopulated before the manager pod starts.

If the Secret is empty, during bootstrapping the Server will generate a certificate and write it into the Secret.

A new webhook server can be created by invoking webhook.NewServer.
The Server will be registered to the provided manager.
You can specify Port, CertDir and various BootstrapOptions.
For the full list of Server options, please see GoDoc.