Kubernetes Webhooks: Concepts and Practice
About 1037 words
What Is a Webhook?
A webhook is a Kubernetes extension mechanism that intercepts and processes API requests before or after they reach the Kubernetes API Server. It lets you extend and customize Kubernetes behavior without modifying its core code.
Types of Webhooks
1. Admission Webhook
- Mutating Webhook: Modifies a resource object before it is persisted.
- Validating Webhook: Checks whether a resource object meets requirements and can reject the request.
2. Authorization Webhook
- Makes custom authorization decisions.
3. Authentication Webhook
- Provides custom authentication.
Use Cases
- Resource validation: Check Pod labels, resource limits, and similar properties.
- Resource mutation: Automatically add sidecar containers, labels, and other fields.
- Security policies: Check image sources, network policies, and similar settings.
- Compliance checks: Ensure resources comply with company policies.
Implementation Steps
Step 1: Create the Webhook Service
First, create a simple webhook service:
// main.go
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"time"
admissionv1 "k8s.io/api/admission/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
)
var (
runtimeScheme = runtime.NewScheme()
codecs = serializer.NewCodecFactory(runtimeScheme)
deserializer = codecs.UniversalDeserializer()
)
type WebhookServer struct {
server *http.Server
}
type patchOperation struct {
Op string `json:"op"`
Path string `json:"path"`
Value interface{} `json:"value,omitempty"`
}
func (whsvr *WebhookServer) mutate(ar *admissionv1.AdmissionReview) *admissionv1.AdmissionResponse {
req := ar.Request
var pod corev1.Pod
if err := json.Unmarshal(req.Object.Raw, &pod); err != nil {
return &admissionv1.AdmissionResponse{
Result: &metav1.Status{
Message: err.Error(),
},
}
}
// Check whether the Pod already has the specified label
if pod.Labels["webhook-demo"] == "true" {
return &admissionv1.AdmissionResponse{
Allowed: true,
}
}
// Create patch operations
patch := []patchOperation{
{
Op: "add",
Path: "/metadata/labels",
Value: map[string]string{"webhook-demo": "true"},
},
}
patchBytes, err := json.Marshal(patch)
if err != nil {
return &admissionv1.AdmissionResponse{
Result: &metav1.Status{
Message: err.Error(),
},
}
}
return &admissionv1.AdmissionResponse{
Allowed: true,
Patch: patchBytes,
PatchType: func() *admissionv1.PatchType {
pt := admissionv1.PatchTypeJSONPatch
return &pt
}(),
}
}
func (whsvr *WebhookServer) serve(w http.ResponseWriter, r *http.Request) {
var body []byte
if r.Body != nil {
if data, err := io.ReadAll(r.Body); err == nil {
body = data
}
}
// Validate Content-Type
if contentType := r.Header.Get("Content-Type"); contentType != "application/json" {
http.Error(w, "invalid Content-Type", http.StatusBadRequest)
return
}
var admissionResponse *admissionv1.AdmissionResponse
ar := admissionv1.AdmissionReview{}
if _, _, err := deserializer.Decode(body, nil, &ar); err != nil {
admissionResponse = &admissionv1.AdmissionResponse{
Result: &metav1.Status{
Message: err.Error(),
},
}
} else {
admissionResponse = whsvr.mutate(&ar)
}
ar.Response = admissionResponse
resp, err := json.Marshal(ar)
if err != nil {
http.Error(w, fmt.Sprintf("could not encode response: %v", err), http.StatusInternalServerError)
}
w.Header().Set("Content-Type", "application/json")
w.Write(resp)
}
func main() {
webhookServer := &WebhookServer{
server: &http.Server{
Addr: ":8443",
TLSConfig: &tls.Config{},
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
},
}
mux := http.NewServeMux()
mux.HandleFunc("/mutate", webhookServer.serve)
webhookServer.server.Handler = mux
fmt.Println("Starting webhook server on :8443")
if err := webhookServer.server.ListenAndServeTLS("/etc/webhook/certs/tls.crt", "/etc/webhook/certs/tls.key"); err != nil {
panic(err)
}
}Step 2: Create a Dockerfile
# Dockerfile
FROM golang:1.21-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o webhook-server .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/webhook-server .
COPY --from=builder /app/certs /etc/webhook/certs
EXPOSE 8443
CMD ["./webhook-server"]Step 3: Create Kubernetes Resources
Create the Namespace and RBAC Resources
# namespace.yaml
apiVersion: v1
kind: Namespace
metadata:
name: webhook-demo# rbac.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: webhook-sa
namespace: webhook-demo
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: webhook-role
rules:
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list", "watch"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: webhook-role-binding
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: webhook-role
subjects:
- kind: ServiceAccount
name: webhook-sa
namespace: webhook-demoCreate the Deployment and Service
# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: webhook-server
namespace: webhook-demo
spec:
replicas: 1
selector:
matchLabels:
app: webhook-server
template:
metadata:
labels:
app: webhook-server
spec:
serviceAccountName: webhook-sa
containers:
- name: webhook-server
image: your-registry/webhook-server:latest
ports:
- containerPort: 8443
volumeMounts:
- name: webhook-certs
mountPath: /etc/webhook/certs
readOnly: true
volumes:
- name: webhook-certs
secret:
secretName: webhook-certs
---
apiVersion: v1
kind: Service
metadata:
name: webhook-server
namespace: webhook-demo
spec:
ports:
- port: 443
targetPort: 8443
selector:
app: webhook-serverCreate the MutatingWebhookConfiguration
# webhook-config.yaml
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
name: webhook-demo
webhooks:
- name: webhook-demo.example.com
rules:
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE"]
resources: ["pods"]
scope: "Namespaced"
clientConfig:
service:
namespace: webhook-demo
name: webhook-server
path: "/mutate"
port: 443
admissionReviewVersions: ["v1"]
sideEffects: None
timeoutSeconds: 5Step 4: Generate TLS Certificates
# Generate a private key
openssl genrsa -out webhook-server-tls.key 2048
# Generate a certificate signing request
openssl req -new -key webhook-server-tls.key -subj "/CN=webhook-server.webhook-demo.svc" -out webhook-server-tls.csr
# Generate a self-signed certificate
openssl x509 -req -in webhook-server-tls.csr -signkey webhook-server-tls.key -out webhook-server-tls.crt -days 365
# Create a Kubernetes Secret
kubectl create secret tls webhook-certs \
--key webhook-server-tls.key \
--cert webhook-server-tls.crt \
--namespace webhook-demoStep 5: Deploy and Test
# Deploy all resources
kubectl apply -f namespace.yaml
kubectl apply -f rbac.yaml
kubectl apply -f deployment.yaml
kubectl apply -f webhook-config.yaml
# Test the webhook
kubectl run test-pod --image=nginx --namespace=webhook-demo
# Check whether the Pod was modified
kubectl get pod test-pod -n webhook-demo -o yaml | grep -A 5 labelsAdvanced Features
1. Conditional Mutation
// Apply the webhook only in a specific namespace
if pod.Namespace != "webhook-demo" {
return &admissionv1.AdmissionResponse{
Allowed: true,
}
}2. Complex Validation Logic
// Validate image sources
for _, container := range pod.Spec.Containers {
if !strings.HasPrefix(container.Image, "your-registry.com/") {
return &admissionv1.AdmissionResponse{
Allowed: false,
Result: &metav1.Status{
Message: "Only images from your-registry.com are allowed",
},
}
}
}3. Error Handling and Retries
// Add retry logic
if err != nil {
log.Printf("Error processing webhook: %v", err)
return &admissionv1.AdmissionResponse{
Allowed: false,
Result: &metav1.Status{
Code: 500,
Message: "Internal server error",
},
}
}Considerations
- Performance: Webhooks increase API request latency, so keep them lightweight.
- Availability: An unavailable webhook service can affect the entire cluster.
- Security: Use TLS certificates and restrict access permissions.
- Monitoring: Monitor webhook performance and error rates.
- Testing: Thoroughly test webhook logic in a test environment.
Summary
Kubernetes webhooks provide powerful extension capabilities, allowing you to customize cluster behavior without modifying core code. With careful design and implementation, you can build capable, secure, and reliable webhook services.
Key points:
- Choose the appropriate webhook type: Mutating or Validating.
- Implement correct admission logic.
- Configure suitable RBAC permissions.
- Use TLS certificates to ensure security.
- Monitor and maintain the webhook service.