Lesson 41 · Section 3: Scheduling
Lesson 41: Validating and mutating admission controllers: webhooks and policies
How the API server lets your own code change or reject requests: mutating and validating webhooks, the order they run in, how a webhook is registered, admission policies written in CEL, and how to find and fix a webhook that blocks the cluster. · 22 min read · 4 min video
Official competencies this lesson covers
Narrated by the local narrator voice. Keys: Space plays and pauses, J and L step, C captions, F full screen.
Why they exist
RBAC answers one question: may this user create Pods in this namespace? It cannot look inside the Pod. It cannot
say "only images from our registry", "every Deployment needs an owner label" or "add the logging sidecar to
everything in prod". Rules about the content of an object belong to admission control, the step that runs after
authorization and before the object is stored.
The built-in admission plugins from the previous lesson cover the rules Kubernetes itself needs. For your own rules,
recompiling the API server is not an option, so two of the built-in plugins exist only to hand the decision to
someone else: MutatingAdmissionWebhook and ValidatingAdmissionWebhook. They are enabled by default.
Mutating and validating
| Mutating admission | Validating admission | |
|---|---|---|
| Can it change the object? | Yes | No |
| Can it reject the request? | Yes | Yes |
| When it runs | First, before schema validation | Last, just before etcd |
| How several run | One after the other, each sees the previous changes | In parallel, all must agree |
| Built-in examples | DefaultStorageClass, ServiceAccount, LimitRanger (defaults) | NamespaceLifecycle, ResourceQuota, PodSecurity |
| Your own | MutatingWebhookConfiguration, MutatingAdmissionPolicy | ValidatingWebhookConfiguration, ValidatingAdmissionPolicy |
Some built-in plugins are both. LimitRanger first fills in missing requests and limits (mutating), then rejects
containers that break the range (validating). ServiceAccount adds the default service account and its token
volume, and rejects a Pod that names a service account that does not exist.
Admission only sees requests that write: create, update, delete, and connect operations such as exec. Reads
(get, list, watch) never pass through admission, so a webhook cannot hide objects from anyone.
The order of things
Parts:
- kubectl (create Pod web)
- Who and may they? (authn, then RBAC)
- Mutating admission (may change the object)
- Schema validation (fields and types)
- Validating admission (yes or no, no edits)
- etcd (object is stored)
Connections:
- kubectl to Who and may they?: request
- Who and may they? to Mutating admission: allowed
- Mutating admission to Schema validation: final object
- Schema validation to Validating admission: valid
- Validating admission to etcd: admit
- Authentication and authorization. A request that RBAC forbids never reaches admission.
- Mutating admission. Built-in mutating plugins, mutating admission policies and mutating webhooks change the object. Mutating webhooks are called one at a time, and each receives the object as the previous one left it.
- Schema validation. The (possibly changed) object is checked against the schema of its kind. A webhook that patches in an invalid field makes the request fail here.
- Validating admission. Built-in validating plugins, validating admission policies and validating webhooks look at the final object. Validating webhooks are called in parallel; a single "no" rejects the request.
- etcd. Only now is the object written.
Why this order? If validation ran first, a later mutation could slip in something that was never checked. With mutation first, validators are guaranteed to judge exactly what will be stored. That is also the rule of thumb for your own design: use a mutating webhook to fix or complete objects, and a validating webhook to enforce, never the other way around.
How a webhook works
Parts:
- kubectl (create Pod web)
- API server (admission phase)
- Webhook config (rules, service, CA)
- Service (pod-policy:443), in namespace webhooks
- Webhook server (HTTPS, your code), in namespace webhooks
Connections:
- kubectl to API server: request
- Webhook config to API server: which requests
- API server to Service: review
- Service to Webhook server: forwards
- Webhook server to API server: allowed: true/false
An admission webhook has two halves:
- A webhook server: any HTTPS server, usually a Deployment with a Service in the cluster (it can also be a URL outside the cluster). cert-manager, ingress-nginx, Istio, Kyverno and OPA Gatekeeper each bring one.
- A webhook configuration: a cluster-scoped API object,
ValidatingWebhookConfigurationorMutatingWebhookConfiguration, that tells the API server which requests to send and where.
For every request that matches the rules, the API server posts an AdmissionReview to the server and waits for the
answer. The server replies allowed: true or allowed: false with a message; a mutating webhook may attach a JSON
patch. The webhook server never writes the object itself: it only answers.
Read this configuration once field by field. It is all you need to understand any webhook you meet:
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration # or MutatingWebhookConfiguration: same fields
metadata:
name: pod-policy # cluster-scoped: no namespace
webhooks:
- name: pods.policy.example.com # shown in error messages
rules: # WHICH requests are sent
- apiGroups: [""]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["pods"]
scope: Namespaced
namespaceSelector: # ...and only from these namespaces
matchExpressions:
- key: kubernetes.io/metadata.name
operator: NotIn
values: ["kube-system", "webhooks"]
clientConfig: # WHERE they are sent
service:
namespace: webhooks
name: pod-policy
path: /validate
port: 443
caBundle: LS0tLS1CRUdJTi... # base64 CA that signed the server's certificate
failurePolicy: Fail # server unreachable: Fail (reject) or Ignore (let through)
timeoutSeconds: 5 # 1 to 30, default 10
sideEffects: None # required: None or NoneOnDryRun
admissionReviewVersions: ["v1"] # required
| Field | What it decides | Default |
|---|---|---|
rules | Operations, API groups, versions and resources that trigger a call | None: required |
namespaceSelector, objectSelector | Limit calls by labels on the namespace or on the object | Everything matches |
matchConditions | Extra CEL filters, for example skip requests from a given user | None |
clientConfig.service or clientConfig.url | The Service (with path and port) or external URL to call | Port 443 |
clientConfig.caBundle | CA certificate the API server uses to verify the webhook server | The API server's system roots |
failurePolicy | What to do on a timeout or connection error | Fail |
timeoutSeconds | How long the API server waits | 10 |
reinvocationPolicy (mutating only) | IfNeeded lets the webhook run again if a later plugin changed the object | Never |
Three things in that list cause most real outages:
- TLS is mandatory. The server's certificate must be valid for the name
<service>.<namespace>.svc, andcaBundlemust hold the CA that signed it. Tools such as cert-manager fill incaBundlefor you. failurePolicy: Failis the default. If the webhook server is down, every matching request is rejected. That is the safe choice for security rules and a dangerous one for availability.- A webhook can block its own repair. A webhook that matches all Pods in all namespaces, and whose server is
down, also rejects the new Pod that would bring the server back. Always exclude the webhook's own namespace and
kube-systemwith anamespaceSelector.
Under the hood · What travels over the wire: AdmissionReview
The API server sends a JSON AdmissionReview with a request. The interesting parts are who is asking, what they
do, and the object itself (oldObject is filled in for updates and deletes):
{
"apiVersion": "admission.k8s.io/v1",
"kind": "AdmissionReview",
"request": {
"uid": "705ab4f5-6393-11e8-b7cc-42010a800002",
"kind": { "group": "", "version": "v1", "kind": "Pod" },
"operation": "CREATE",
"namespace": "team-a",
"userInfo": { "username": "jane", "groups": ["developers"] },
"object": { "apiVersion": "v1", "kind": "Pod", "...": "the whole Pod" },
"dryRun": false
}
}
The server answers with the same uid. A validating webhook that rejects:
{
"apiVersion": "admission.k8s.io/v1",
"kind": "AdmissionReview",
"response": {
"uid": "705ab4f5-6393-11e8-b7cc-42010a800002",
"allowed": false,
"status": { "code": 403, "message": "image must come from registry.example.com" }
}
}
A mutating webhook that accepts and changes the object returns a JSON patch, base64 encoded. This one decodes
to [{"op": "add", "path": "/spec/replicas", "value": 3}]:
{
"apiVersion": "admission.k8s.io/v1",
"kind": "AdmissionReview",
"response": {
"uid": "705ab4f5-6393-11e8-b7cc-42010a800002",
"allowed": true,
"patchType": "JSONPatch",
"patch": "W3sib3AiOiAiYWRkIiwgInBhdGgiOiAiL3NwZWMvcmVwbGljYXMiLCAidmFsdWUiOiAzfV0="
}
}
Two consequences of this design. A mutating webhook must be idempotent: it may be called again on an object it
already changed (after another plugin modified it, with reinvocationPolicy: IfNeeded), and the result must be the
same. And a webhook should have no side effects: a request it allowed can still be rejected by the next
controller, so anything it did outside the answer would be left behind. That is what sideEffects: None promises,
and it is why kubectl apply --dry-run=server can safely call your webhooks.
Webhook, policy or built-in plugin
Parts:
- API request (create, update, delete)
- Built-in plugins (compiled in, by flag), in kube-apiserver
- Admission policies (CEL rules as objects), in kube-apiserver
- Webhook plugins (call out over HTTPS), in kube-apiserver
- Webhook server (a Pod you run)
Connections:
- API request to Built-in plugins
- API request to Admission policies
- API request to Webhook plugins
- Webhook plugins to Webhook server: review
A webhook is powerful, but it is one more server that has to be deployed, secured with certificates and kept running. For rules that only need to look at the object, Kubernetes has admission policies: the rule is a CEL expression stored in an API object, and the API server evaluates it itself.
| Built-in plugin | Admission webhook | Admission policy | |
|---|---|---|---|
| Where the logic runs | Inside kube-apiserver | Your HTTPS server | Inside kube-apiserver |
| How you add a rule | --enable-admission-plugins on the API server | A webhook configuration and a running server | A policy object and a binding |
| Language | Go, compiled in | Anything | CEL expressions |
| Can call other systems | No | Yes (image scanners, external databases) | No |
| If it is unavailable | Cannot be | failurePolicy decides | Cannot be |
| Kinds | The fixed list | ValidatingWebhookConfiguration, MutatingWebhookConfiguration | ValidatingAdmissionPolicy, MutatingAdmissionPolicy |
A policy does nothing until a binding switches it on. The policy says what to check; the binding says where (which namespaces or objects) and how strictly:
validationActions | Effect of a failed check |
|---|---|
Deny | The request is rejected |
Warn | The request is accepted and kubectl prints a warning |
Audit | The request is accepted and the failure is recorded in the audit log |
Deny and Warn cannot be combined. A common rollout is [Warn, Audit] first, then [Deny] once nothing
legitimate trips the rule.
ValidatingAdmissionPolicy is stable and enabled by default. MutatingAdmissionPolicy is newer and works the same
way with a mutations list instead of validations; check kubectl api-resources --api-group=admissionregistration.k8s.io
to see what your cluster serves.
Using it
Example · Find out what rejected your Pods
A Deployment was created without any error, but it stays at 0/3 and there are no Pods to describe. The Deployment
itself was admitted; its Pods are created later by the ReplicaSet controller, and that is where admission said
no:
kubectl get deploy web # READY 0/3
kubectl describe rs -l app=web # read the Events
Warning FailedCreate replicaset-controller Error creating: admission webhook "pods.policy.example.com"
denied the request: image must come from registry.example.com
The message contains the webhook's name and its reason. To see who owns it and what it matches:
kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations
kubectl get validatingwebhookconfiguration pod-policy -o yaml
Here the fix is in your own object: use an allowed image (kubectl set image deploy/web web=registry.example.com/web:1.4).
Before you apply a change, you can ask admission without creating anything:
kubectl apply -f web.yaml --dry-run=server # runs admission, including webhooks, and stores nothing
Example · Repair a webhook that cannot be reached
Creating any Pod fails, even a trivial one:
kubectl run test --image=nginx:1.29-alpine
Error from server (InternalError): Internal error occurred: failed calling webhook "pods.policy.example.com":
failed to call webhook: Post "https://pod-policy.webhooks.svc:443/validate?timeout=5s": no endpoints available
for service "pod-policy"
failed calling webhook means the server did not answer, and failurePolicy: Fail turned that into a rejection.
The URL in the message gives you the Service (pod-policy) and namespace (webhooks). The last part tells you
which link is broken:
| The message ends with | Cause | Where to look |
|---|---|---|
service "pod-policy" not found | The Service is missing, or the configuration names the wrong one | clientConfig.service in the configuration |
no endpoints available for service | No ready Pod behind the Service | The webhook Deployment and the Service selector |
connection refused | Wrong port or targetPort | The Service and the container port |
context deadline exceeded | The server is too slow, or a NetworkPolicy blocks the API server | Webhook logs, NetworkPolicies |
x509: certificate signed by unknown authority | caBundle does not match the server's certificate | caBundle, the TLS Secret |
Walk the chain from the configuration to the Pod:
kubectl get validatingwebhookconfiguration pod-policy -o jsonpath='{.webhooks[*].clientConfig.service}'
kubectl -n webhooks get svc,endpointslices,deploy,pods
kubectl -n webhooks describe deploy pod-policy
kubectl -n webhooks logs deploy/pod-policy
If the webhook's own Pod cannot be created because the webhook rejects it, break the loop first. Let requests through while the server is down, then repair it and switch back:
kubectl patch validatingwebhookconfiguration pod-policy --type=json \
-p='[{"op": "replace", "path": "/webhooks/0/failurePolicy", "value": "Ignore"}]'
# ...fix the Deployment, wait until it is Ready...
kubectl patch validatingwebhookconfiguration pod-policy --type=json \
-p='[{"op": "replace", "path": "/webhooks/0/failurePolicy", "value": "Fail"}]'
The blunt alternative is to save and delete the configuration, and re-apply it afterwards:
kubectl get validatingwebhookconfiguration pod-policy -o yaml > /tmp/pod-policy.yaml
kubectl delete validatingwebhookconfiguration pod-policy
Either way the rule is not enforced in the meantime, so keep that window short.
Example · Register a webhook server you were given
You get an image for a webhook server, a server certificate (tls.crt, tls.key) issued for
pod-policy.webhooks.svc, and the CA that signed it (ca.crt). Deploy the server first, the configuration last:
kubectl create namespace webhooks
kubectl -n webhooks create secret tls pod-policy-tls --cert=tls.crt --key=tls.key
kubectl -n webhooks create deployment pod-policy --image=registry.example.com/pod-policy:1.0 --port=8443 \
--dry-run=client -o yaml > deploy.yaml # add a volume and mount for the secret pod-policy-tls
kubectl apply -f deploy.yaml
kubectl -n webhooks expose deployment pod-policy --port=443 --target-port=8443
kubectl -n webhooks rollout status deployment pod-policy
Then put the CA into the configuration from earlier in this lesson and apply it:
base64 -w0 ca.crt # paste the output as clientConfig.caBundle
kubectl apply -f pod-policy-webhook.yaml
Test both outcomes:
kubectl run ok --image=registry.example.com/web:1.4 --dry-run=server
kubectl run bad --image=nginx:1.29-alpine --dry-run=server # admission webhook ... denied the request
Create the configuration only when the server is Ready. With failurePolicy: Fail, a configuration that points at
a server that is not there yet rejects every matching request from the first second.
Example · Enforce a rule without any server
No Deployment in a test namespace may have more than 5 replicas. Write the rule as a policy, and bind it to
namespaces labelled environment=test:
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: max-replicas
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: ["apps"]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["deployments"]
validations:
- expression: "object.spec.replicas <= 5"
message: "Deployments in test namespaces may have at most 5 replicas"
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: max-replicas-test
spec:
policyName: max-replicas
validationActions: [Deny]
matchResources:
namespaceSelector:
matchLabels:
environment: test
kubectl apply -f max-replicas.yaml
kubectl label namespace team-a environment=test
kubectl -n team-a create deployment big --image=nginx:1.29-alpine --replicas=6 --dry-run=client -o yaml > big.yaml
kubectl apply -f big.yaml
The deployments "big" is invalid: : ValidatingAdmissionPolicy 'max-replicas' with binding 'max-replicas-test'
denied request: Deployments in test namespaces may have at most 5 replicas
The same Deployment in a namespace without the label is accepted, and so is kubectl scale up to 5. In the
expression, object is the incoming object and oldObject the stored one; request and namespaceObject are also
available.
Tricks
Common mistakes
- Expecting a validating webhook to fix the object. It can only accept or reject. Anything that sets defaults or injects containers must be a mutating webhook or a mutating admission policy.
- Validating in a mutating webhook. Other mutating controllers run after it and may change the object again. Enforce rules in the validating phase, which sees the final object.
- Matching everything with
failurePolicy: Fail. A webhook for all Pods in all namespaces blocks its own restart and the system Pods when its server is down. Excludekube-systemand the webhook's namespace. - Applying the configuration before the server is ready. Requests are rejected from that moment on. Deploy and check the server, then register it.
- A certificate for the wrong name. The certificate must cover
<service>.<namespace>.svc, andcaBundlemust be the base64 of the CA, not of the server certificate's key or a file path. - Writing a policy and forgetting the binding. A
ValidatingAdmissionPolicywithout aValidatingAdmissionPolicyBindingchecks nothing. - Looking for the webhook in a namespace. Webhook configurations and admission policies are cluster-scoped; only the server and its Service live in a namespace.
Recap
- Mutating admission may change an object; validating admission only accepts or rejects it.
- The order is fixed: mutate, check the schema, validate, store. Validators see the final object.
- A webhook is an HTTPS server plus a
MutatingWebhookConfigurationorValidatingWebhookConfigurationthat says which requests go to which Service;failurePolicydecides what happens when it is down. - A
ValidatingAdmissionPolicywith a binding enforces a CEL rule inside the API server, with no server to run. denied the request: fix your object.failed calling webhook: fix the webhook, or relax itsfailurePolicy.
Official docs
Quiz: check what you learned
5 questions on this lesson · about 3 min · instant feedback. Missed questions come back in your review queue.
Sign in to take the quiz and keep your score.
Practise: try it on a real cluster
2 hands-on labs for this lesson. You get goals, not steps: any solution that reaches them passes.
Section capstone on a three-node cluster. Reserve a node for one team, keep a search engine on fast disks, run an agent on every node whatever its taints, set resource defaults for a namespace, and place a Pod no scheduler will take.
Build · Level 3 · challenge · target 35 min
Unblock a namespace held up by a dead admission webhook, then write an admission policy that turns away pods without an owner label in one namespace only.
Build · Level 3 · challenge · target 20 min
Discussion
Learners ask and answer questions here. Sign in to read and join the discussion.