What Is Mutating Webhook in Kubernetes: Simple Explanation & Example
mutating webhook in Kubernetes is a special HTTP callback that intercepts requests to the Kubernetes API server and can modify the objects before they are saved. It allows automatic changes like adding labels or injecting sidecars to pods during creation or update.How It Works
Imagine you are sending a letter, but before it reaches the recipient, a helper reads it and can add or change some details automatically. In Kubernetes, a mutating webhook acts like that helper. When you create or update a resource like a pod, the webhook gets a chance to look at the request and change it before Kubernetes saves it.
This happens because Kubernetes API server sends the resource data to the webhook service via an HTTP call. The webhook then responds with changes it wants to make. For example, it can add extra environment variables, labels, or even inject containers into pods. This process helps automate common tasks and enforce policies without manual edits.
Example
This example shows a simple mutating webhook configuration that adds a label to every pod created in the cluster.
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
name: add-label-webhook
webhooks:
- name: add-label.example.com
clientConfig:
service:
name: label-adder-service
namespace: default
path: "/mutate"
caBundle: <base64-encoded-CA-cert>
rules:
- operations: ["CREATE"]
apiGroups: [""]
apiVersions: ["v1"]
resources: ["pods"]
admissionReviewVersions: ["v1", "v1beta1"]
sideEffects: NoneWhen to Use
Use mutating webhooks when you want to automatically change Kubernetes objects as they are created or updated. Common uses include:
- Injecting sidecar containers for logging or monitoring
- Adding default labels or annotations for tracking
- Enforcing security policies by modifying pod specs
- Automatically setting resource limits or environment variables
They help keep your cluster consistent and reduce manual work by automating repetitive changes.
Key Points
- Mutating webhooks modify Kubernetes objects during API requests.
- They run before the object is saved, allowing automatic changes.
- Configured via
MutatingWebhookConfigurationresources. - Commonly used for injecting sidecars or adding labels.
- Must be carefully designed to avoid infinite loops or delays.