Skip to content
LF Cert Trainer

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

1/10Validating and mutating admission
0:00 / 3:37

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 admissionValidating admission
Can it change the object?YesNo
Can it reject the request?YesYes
When it runsFirst, before schema validationLast, just before etcd
How several runOne after the other, each sees the previous changesIn parallel, all must agree
Built-in examplesDefaultStorageClass, ServiceAccount, LimitRanger (defaults)NamespaceLifecycle, ResourceQuota, PodSecurity
Your ownMutatingWebhookConfiguration, MutatingAdmissionPolicyValidatingWebhookConfiguration, 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

Mutate first, validate lastrequestallowedfinal objectvalidadmitkubectlcreate Pod webWho and may they?authn, then RBACMutating admissionmay change the objectSchema validationfields and typesValidating admissionyes or no, no editsetcdobject is stored
Mutate first, validate last. Everything that may change the object runs before anything that only judges it, so validators always see the final version.

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
  1. Authentication and authorization. A request that RBAC forbids never reaches admission.
  2. 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.
  3. 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.
  4. 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.
  5. 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

One admission webhook callnamespace webhooksrequestwhich requestsreviewforwardsallowed: true/falsekubectlcreate Pod webAPI serveradmission phaseWebhook configrules, service, CAServicepod-policy:443Webhook serverHTTPS, your code
One admission webhook call. The webhook configuration tells the API server which requests to send and where. The server only answers; it never talks to etcd for you.

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, ValidatingWebhookConfiguration or MutatingWebhookConfiguration, 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
FieldWhat it decidesDefault
rulesOperations, API groups, versions and resources that trigger a callNone: required
namespaceSelector, objectSelectorLimit calls by labels on the namespace or on the objectEverything matches
matchConditionsExtra CEL filters, for example skip requests from a given userNone
clientConfig.service or clientConfig.urlThe Service (with path and port) or external URL to callPort 443
clientConfig.caBundleCA certificate the API server uses to verify the webhook serverThe API server's system roots
failurePolicyWhat to do on a timeout or connection errorFail
timeoutSecondsHow long the API server waits10
reinvocationPolicy (mutating only)IfNeeded lets the webhook run again if a later plugin changed the objectNever

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, and caBundle must hold the CA that signed it. Tools such as cert-manager fill in caBundle for you.
  • failurePolicy: Fail is 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-system with a namespaceSelector.
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

Three places admission logic can livekube-apiserverreviewAPI requestcreate, update, deleteBuilt-in pluginscompiled in, by flagAdmission policiesCEL rules as objectsWebhook pluginscall out over HTTPSWebhook servera Pod you run
Three places admission logic can live. Built-in plugins and admission policies run inside the API server. Only a webhook depends on something else being up.

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 pluginAdmission webhookAdmission policy
Where the logic runsInside kube-apiserverYour HTTPS serverInside kube-apiserver
How you add a rule--enable-admission-plugins on the API serverA webhook configuration and a running serverA policy object and a binding
LanguageGo, compiled inAnythingCEL expressions
Can call other systemsNoYes (image scanners, external databases)No
If it is unavailableCannot befailurePolicy decidesCannot be
KindsThe fixed listValidatingWebhookConfiguration, MutatingWebhookConfigurationValidatingAdmissionPolicy, 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:

validationActionsEffect of a failed check
DenyThe request is rejected
WarnThe request is accepted and kubectl prints a warning
AuditThe 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 withCauseWhere to look
service "pod-policy" not foundThe Service is missing, or the configuration names the wrong oneclientConfig.service in the configuration
no endpoints available for serviceNo ready Pod behind the ServiceThe webhook Deployment and the Service selector
connection refusedWrong port or targetPortThe Service and the container port
context deadline exceededThe server is too slow, or a NetworkPolicy blocks the API serverWebhook logs, NetworkPolicies
x509: certificate signed by unknown authoritycaBundle does not match the server's certificatecaBundle, 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. Exclude kube-system and 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, and caBundle must 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 ValidatingAdmissionPolicy without a ValidatingAdmissionPolicyBinding checks 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 MutatingWebhookConfiguration or ValidatingWebhookConfiguration that says which requests go to which Service; failurePolicy decides what happens when it is down.
  • A ValidatingAdmissionPolicy with 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 its failurePolicy.

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.