Admission Controllers are plugins that intercept requests to the Kubernetes API after authentication and authorization, but before the object is persisted in etcd. They can validate (accept or reject) or mutate (modify) resources. This mechanism is the foundation of policy-as-code on Kubernetes.
What you will learn
- Place admission controllers in the path of a request, between authorization and the write to etcd.
- Tell a mutating controller from a validating one, and say why the mutating ones run first.
- List the built-in controllers active on a cluster, and configure Pod Security Admission through namespace labels.
- Read an admission webhook and say what
failurePolicycauses when the service does not answer. - Read a ValidatingAdmissionPolicy and a MutatingAdmissionPolicy, which validate and modify in CEL without a webhook.
- Choose between native CEL policies, Kyverno and Gatekeeper, then find the webhook at fault when a creation fails or times out.
How do Admission Controllers work?
When you create a resource with kubectl apply, the request goes through several stages:
The 2 types of admission controllers
Admission controllers fall into two categories, which act at different moments of the request lifecycle. This distinction drives everything else: it tells you which of the two meets your need.
| Type | Role | Example |
|---|---|---|
| Mutating | Modifies the resource before persistence | Inject a sidecar, add labels |
| Validating | Accepts or rejects the resource | Block privileged pods, require labels |
Take the creation of a pod. A mutating controller adds the label team: backend to every pod in a given namespace. A validating controller then checks that the label is present. If the developer forgot it in the manifest, the mutation has already set it and the validation passes: the execution order is what makes this combination usable.
Built-in Admission Controllers
Kubernetes ships with many admission controllers enabled by default. Nothing to install: they are part of the API Server. The --enable-admission-plugins flag, passed when the API Server starts, lets you enable others.
For the CKS certification and for production security, some controllers matter more than others. Here are the main ones and why.
Security controllers
These controllers protect your cluster against dangerous configurations and privilege escalation.
| Controller | Type | Role | In the binary's default list |
|---|---|---|---|
| PodSecurity | Validating | Enforces the Pod Security Standards | Yes |
| NodeRestriction | Validating | Limits what kubelets can modify | No, added by kubeadm |
| ServiceAccount | Mutating | Injects the ServiceAccount token | Yes |
| AlwaysPullImages | Mutating + Validating | Forces imagePullPolicy: Always | No |
PodSecurity rejects pods whose securityContext exceeds the level allowed on the namespace. Without it, any account that can create a pod can ask for privileged mode, which gives the container full access to the devices and the kernel of the host node, and therefore to every other pod running there.
NodeRestriction prevents a compromised node from modifying resources that do not belong to it: a malicious kubelet cannot modify the pods of another node. It is not in the default list of the kube-apiserver binary. kubeadm adds it, with --enable-admission-plugins=NodeRestriction, as the command in the next section shows on a kind cluster running 1.37. On a distribution that does not go through kubeadm, check that it is there; do not assume it.
AlwaysPullImages has two types because it acts twice. Its mutating part forces imagePullPolicy: Always on every Pod created, its validating part checks on UPDATE that the value has not been set back to something else. What is at stake is multi-tenancy: without it, a Pod can reuse a private image already present on the node, pulled by another namespace with its own credentials, without ever proving that it is entitled to it.
Resource controllers
These controllers manage quotas and limits so that one namespace cannot consume all the resources of the cluster.
| Controller | Type | Role | In the binary's default list |
|---|---|---|---|
| LimitRanger | Mutating + Validating | Applies default limits | Yes |
| ResourceQuota | Validating | Checks namespace quotas | Yes |
| DefaultStorageClass | Mutating | Adds the default StorageClass | Yes |
If you create a pod without resources.limits, LimitRanger can add default limits, defined in a LimitRange object. It is a mutation, which prevents pods without limits from consuming all the resources of a node.
ResourceQuota, for its part, validates that creating a resource does not exceed the namespace quotas. If your namespace is limited to 10 pods and you try to create an 11th, ResourceQuota rejects it.
Seeing the active controllers
The effective list lives in the startup arguments of the API Server, not in a Kubernetes resource you can query. There are two ways to read it, depending on your access. From kubectl, target the pod by its label, not by a name pattern: kube-apiserver-* would be expanded by your shell against the files of the current directory and would never reach kubectl. From a kubeadm control plane node, the static manifest gives the same information without going through the API.
# Enabled controllers, seen from the API (kubeadm cluster)kubectl get pods -n kube-system -l component=kube-apiserver \ -o jsonpath='{.items[*].spec.containers[*].command}' | tr ' ' '\n' | \ grep admission-plugins
# Or via the static manifest, on a control plane nodegrep admission-plugins /etc/kubernetes/manifests/kube-apiserver.yamlOn a distribution that does not expose the API Server as a static Pod (k3s or a managed offering), neither command returns anything. The configuration is carried by the distribution or by the provider, and is not always editable.
What this command does not tell you
On a kubeadm cluster, the output fits on one line, and it is misleading:
--enable-admission-plugins=NodeRestrictionIt would be wrong to conclude that only one controller is active. The flag is called "enable", but its documentation says precisely this: admission plugins that should be enabled in addition to default enabled ones. It adds to a default list, it does not replace it.
This default list is written in no file of the cluster: only the binary knows it. You read it in its help output. Since the image is distroless (no shell), you call the binary directly:
kubectl -n kube-system exec kube-apiserver-<node> -- \ kube-apiserver --help | grep -A2 'enable-admission-plugins'In Kubernetes 1.37, it holds twenty-five controllers:
NamespaceLifecycle, LimitRanger, ServiceAccount, TaintNodesByCondition,PodSecurity, Priority, DefaultTolerationSeconds, DefaultStorageClass,StorageObjectInUseProtection, PodGroupProtection, PersistentVolumeClaimResize,RuntimeClass, CertificateApproval, CertificateSigning, ClusterTrustBundleAttest,CertificateSubjectRestriction, DefaultIngressClass, PodTopologyLabels,NodeDeclaredFeatureValidator, PodResizeValidator, MutatingAdmissionPolicy,MutatingAdmissionWebhook, ValidatingAdmissionPolicy, ValidatingAdmissionWebhook,ResourceQuotaThree takeaways. PodSecurity is on the list, which explains why the Pod
Security Standards work without installing anything. MutatingAdmissionPolicy
is on it too, next to ValidatingAdmissionPolicy: both native policy engines
are active by default. And NodeRestriction is not on it: that is exactly
why kubeadm adds it with --enable-admission-plugins, and why a distribution
that does not do so leaves its kubelets free to modify any Pod.
To remove a controller from this list, use --disable-admission-plugins,
never an omission in --enable-admission-plugins.
Pod Security Admission (PSA)
Pod Security Admission is the admission controller that enforces the Pod Security Standards. It is enabled by default: it is on the binary's list shown above.
Configuration
PSA is configured through labels on namespaces, which avoids any extra policy object. Three modes coexist and add up: enforce rejects the pod, audit accepts it and records an entry in the audit log, warn accepts it and returns a warning to kubectl.
To deploy without breaking anything, set warn and audit first at the target level, watch what comes up, and only then add enforce.
One point to know about enforce-version: the value latest follows the evolution of the standard, so a Pod accepted today may be rejected after a cluster upgrade. For stable behavior, pin a version, that of your cluster (v1.37 here), on production namespaces.
apiVersion: v1kind: Namespacemetadata: name: production labels: # Level to enforce pod-security.kubernetes.io/enforce: restricted # Version of the standard (latest or v1.xx), pinned in production pod-security.kubernetes.io/enforce-version: v1.37 # Audit mode (logs only) pod-security.kubernetes.io/audit: restricted # Warn mode (shows a warning) pod-security.kubernetes.io/warn: restrictedExemptions
Some system workloads need privileges (CNI, monitoring). Exempt them in the configuration:
# /etc/kubernetes/psa.yaml (API Server config file)apiVersion: apiserver.config.k8s.io/v1kind: AdmissionConfigurationplugins:- name: PodSecurity configuration: apiVersion: pod-security.admission.config.k8s.io/v1 kind: PodSecurityConfiguration defaults: enforce: "baseline" enforce-version: "latest" exemptions: usernames: [] runtimeClasses: [] namespaces: - kube-system - kube-node-leaseCustom webhooks
Beyond the built-in controllers, you can create your own admission controllers through webhooks.
ValidatingWebhookConfiguration
This object contains no logic: it describes where to reach your service and when to call it. The validation code lives in the service referenced by clientConfig, which must answer over HTTPS with a certificate validated by the caBundle.
Three fields determine behavior in production. rules restricts the trigger to the relevant resources and operations, without which you add a network call to every request in the cluster. sideEffects: None declares that the webhook modifies nothing outside its response, which the API Server requires for --dry-run requests. And failurePolicy decides what happens when your service does not answer.
apiVersion: admissionregistration.k8s.io/v1kind: ValidatingWebhookConfigurationmetadata: name: require-labelswebhooks:- name: require-labels.example.com clientConfig: service: name: label-validator namespace: admission path: /validate caBundle: ${CA_BUNDLE} rules: - apiGroups: [""] apiVersions: ["v1"] operations: ["CREATE", "UPDATE"] resources: ["pods"] admissionReviewVersions: ["v1"] sideEffects: None failurePolicy: Fail # Rejects if the webhook is unavailableMutatingWebhookConfiguration
The structure is identical, but this time the service returns a JSON patch applied to the resource before persistence. This is the mechanism behind the sidecar injection of service meshes. Two differences from the previous example deserve attention. The operations are limited to CREATE: the list of containers of a Pod no longer changes after its creation, so a container added during an update would be rejected. And the failurePolicy here is Ignore, a consistent choice for a convenience injection, not one to copy for a mutation that affects security.
apiVersion: admissionregistration.k8s.io/v1kind: MutatingWebhookConfigurationmetadata: name: inject-sidecarwebhooks:- name: inject-sidecar.example.com clientConfig: service: name: sidecar-injector namespace: admission path: /mutate caBundle: ${CA_BUNDLE} rules: - apiGroups: [""] apiVersions: ["v1"] operations: ["CREATE"] resources: ["pods"] admissionReviewVersions: ["v1"] sideEffects: None failurePolicy: Ignore # Accepts if the webhook is unavailableValidatingAdmissionPolicy (VAP) and MutatingAdmissionPolicy (MAP)
Kubernetes now offers a native duo of declarative policies in CEL, with no webhook to maintain:
ValidatingAdmissionPolicy(GA since 1.30) accepts or rejects a resource based on a CEL expression.MutatingAdmissionPolicy(GA since 1.36) modifies the incoming resource (adding a label, a defaultsecurityContext, and so on) in CEL.
Before 1.36, every mutation went through an external webhook: Kyverno, Gatekeeper or in-house code. Now, most simple cases are handled in a few lines of YAML.
Advantages over webhooks
Why prefer VAP to classic webhooks? For two reasons: simplicity and reliability.
A webhook is a service to deploy, TLS certificates to manage, high availability to ensure and code to maintain. If it goes down, your deployments are blocked with failurePolicy: Fail, or accepted without any validation with Ignore.
VAP removes these problems: validation runs directly inside the API Server, with no external network call.
| Criterion | Webhooks | VAP + MAP |
|---|---|---|
| External dependency | Yes (service to maintain) | No (native) |
| Latency | Variable (network call) | Minimal |
| Language | Go, Python, etc. | CEL |
| Complexity | High | Low to medium |
| Validation since K8s | 1.9+ | 1.30+ (stable) |
| Mutation since K8s | 1.9+ | 1.36+ (stable) |
The trade-off? CEL is less flexible than Go or Python code. For simple validations ("this field must exist", "this value is forbidden") and simple mutations (adding a label, a default value), VAP and MAP are enough. For the generation of resources (an auto-created NetworkPolicy), image signature verification (Cosign) or complex business logic, webhooks remain necessary.
VAP example: forbid privileged pods
A VAP policy is always deployed as two objects: the ValidatingAdmissionPolicy carries the rule, the ValidatingAdmissionPolicyBinding decides where it applies. This separation lets you write the rule once and enable it gradually, namespace by namespace, by changing only the binding.
The trap in this example is in the CEL expression. In CEL, reading a missing field raises an error instead of returning an empty value. Yet many containers have no securityContext. An expression written naively as c.securityContext.privileged == true therefore fails on a perfectly normal pod with no such key: securityContext, and since failurePolicy is Fail, the policy blocks every pod creation in the targeted namespace. The fix is the has() operator, which tests that the field is present before reading it.
The expression below also covers initContainers: a privileged init container gets exactly the same access to the node as an application container.
The binding does not target a namespace by its name but by a label environment=production, which Kubernetes does not set by itself. You must label the namespace before the rule applies: otherwise the policy exists, the binding exists, and nothing is rejected.
kubectl create namespace boutiquekubectl label namespace boutique environment=productionkubectl apply -f deny-privileged.yamlapiVersion: admissionregistration.k8s.io/v1kind: ValidatingAdmissionPolicymetadata: name: deny-privilegedspec: failurePolicy: Fail matchConstraints: resourceRules: - apiGroups: [""] apiVersions: ["v1"] operations: ["CREATE", "UPDATE"] resources: ["pods"] validations: - expression: >- !(object.spec.containers + (has(object.spec.initContainers) ? object.spec.initContainers : [])) .exists(c, has(c.securityContext) && has(c.securityContext.privileged) && c.securityContext.privileged) message: "Privileged containers are forbidden"---apiVersion: admissionregistration.k8s.io/v1kind: ValidatingAdmissionPolicyBindingmetadata: name: deny-privileged-bindingspec: policyName: deny-privileged validationActions: - Deny matchResources: namespaceSelector: matchExpressions: - key: environment operator: In values: ["production"]Tested on Kubernetes 1.37 with a privileged: true Pod: rejected in
boutique, created without a word in default, which does not carry the
label. The message cites the policy and the binding, which is enough to trace
back to the rule.
$ kubectl apply -f privileged-pod.yaml -n boutiqueThe pods "privileged-pod" is invalid: : ValidatingAdmissionPolicy 'deny-privileged'with binding 'deny-privileged-binding' denied request: Privileged containers are forbidden$ kubectl apply -f privileged-pod.yaml -n defaultpod/privileged-pod createdMAP example: inject a default label
This policy automatically adds the label team: platform to every pod created in the targeted namespace. The mechanism differs from a mutating webhook: instead of returning a patch, you describe in CEL a partial object that the API Server merges with the incoming resource, using the same semantics as kubectl apply. Fields you do not mention stay untouched: you do not overwrite labels already set by the manifest.
Two fields shape the result. reinvocationPolicy: Never prevents the rule from being re-evaluated after the mutations of other controllers, which is enough here since the operation is idempotent (replaying it gives the same result). And the binding targets the map-test namespace, to be created before you apply it, by the label kubernetes.io/metadata.name, which Kubernetes sets itself on every namespace: no need to label it yourself for this particular case.
apiVersion: admissionregistration.k8s.io/v1kind: MutatingAdmissionPolicymetadata: name: add-team-labelspec: failurePolicy: Fail reinvocationPolicy: Never matchConstraints: resourceRules: - apiGroups: [""] apiVersions: ["v1"] operations: ["CREATE"] resources: ["pods"] mutations: - patchType: ApplyConfiguration applyConfiguration: expression: | Object{ metadata: Object.metadata{ labels: {"team": "platform"} } }---apiVersion: admissionregistration.k8s.io/v1kind: MutatingAdmissionPolicyBindingmetadata: name: add-team-label-bindingspec: policyName: add-team-label matchResources: namespaceSelector: matchLabels: kubernetes.io/metadata.name: map-testThe ValidatingAdmissionPolicy guide details the two patchType values (ApplyConfiguration and JSONPatch) as well as the progressive rollout strategy.
Comparing Policy-as-Code solutions
Several tools can implement policy-as-code on Kubernetes. How do you choose? It depends on your context: CKS preparation, team expertise, functional needs. The detailed comparison, rerun on Kubernetes 1.37, lives in VAP+MAP vs Kyverno vs Gatekeeper.
| Solution | Type | Language | Learning curve | CKS |
|---|---|---|---|---|
| Pod Security Admission | Built-in | Labels | Easy | In the curriculum |
| ValidatingAdmissionPolicy | Built-in | CEL | Medium | In the curriculum |
| MutatingAdmissionPolicy (1.36+) | Built-in | CEL | Medium | In the curriculum |
| Kyverno | Add-on | YAML + CEL | Easy | Out of the curriculum |
| OPA Gatekeeper | Add-on | Rego | Hard | Out of the curriculum |
The table reads as follows:
- PSA is the starting point: enable it on all your namespaces with at least the
baselinelevel. It is fast and effective. - VAP + MAP complement PSA for custom rules that PSA does not cover (forbidding certain images, requiring annotations, injecting a label, setting a default
securityContext). Since 1.36, the duo covers validation and mutation without a webhook. - Kyverno and Gatekeeper bring what VAP and MAP do not cover: automatic generation of resources (NetworkPolicy, Secret, ConfigMap), verification of Cosign image signatures, detailed compliance reports. In exchange, they add operational complexity.
Diagnosis and troubleshooting
A misbehaving admission controller produces misleading symptoms:
a creation rejected with no clear message, a Pod that never appears, or a
kubectl apply that waits until timeoutSeconds (10 s by default) before
failing on a timeout.
The error message helps in part, and it does not say the same thing in each case.
When a webhook rejects the request, it cites its name:
admission webhook "<name>" denied the request: .... You then just find the
configuration of that name in the cluster inventory
(kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations),
and read its rule.
When the call fails with failurePolicy: Fail, the message starts with
failed calling webhook "<name>" and usually contains the URL called,
https://<service>.<namespace>.svc:443/..., which points to the Service to
examine. Real output, taken on Kubernetes 1.37 with Kyverno:
Error from server (InternalError): Internal error occurred: failed calling webhook"mutate.kyverno.svc-fail": failed to call webhook: Post"https://kyverno-svc.kyverno.svc:443/mutate/fail?timeout=10s": dial tcp10.96.174.50:443: connect: connection refusedHere, the webhook name is mutate.kyverno.svc-fail and the Service to examine
is kyverno-svc, in the kyverno namespace. You check its endpoints, then you
read the failurePolicy of the webhook in the inventory.
With failurePolicy: Ignore, the trap is the reverse: the request goes through
with no error on the client side. A line remains in the kube-apiserver log and,
if auditing is enabled, an annotation in the audit log.
Listing the configured webhooks
Faced with a cluster where resource creations fail for no obvious reason, start by taking inventory of the webhooks: they are cluster-scoped objects (they belong to no namespace), often installed by a Helm chart, and therefore invisible in the namespace where the problem shows up. A service mesh, a certificate operator or a policy engine each install at least one. In the describe output, look first at the failurePolicy and the Service field: a webhook set to Fail that points to a service with no endpoint (no Pod behind it) blocks all the requests it covers.
# Validating webhookskubectl get validatingwebhookconfigurations
# Mutating webhookskubectl get mutatingwebhookconfigurations
# Details of one webhookkubectl describe validatingwebhookconfiguration <name>Common errors
When an admission webhook misbehaves, kubectl prints the error when you create the resource, and the end of the message gives the cause. The two subsections below cover the cases you will meet: an unreachable webhook, which answers connection refused or times out, and a call that fails with failed calling webhook, sometimes because of a TLS certificate. Each one says what to check and with which command.
"connection refused" or timeout
This cause often appears inside a failed calling webhook message, as in the output above: it is not a failure distinct from the next one.
The webhook is not reachable. Two causes to check first, in this order:
- The Service exists and points to Pods: its
EndpointSlicelist is not empty. - No NetworkPolicy blocks the traffic coming from the API Server.
kubectl get endpointslice -n <namespace> -l kubernetes.io/service-name=<service-name>kubectl describe service -n <namespace> <service-name>A timeout can also come from a webhook that is too slow, which does not answer
within timeoutSeconds.
"failed calling webhook"
With failurePolicy: Fail, this message is the one for any webhook call that fails, and its end gives the cause: connection refused or a timeout points back to the previous subsection. If the webhook answers but returns an error, check the logs:
kubectl logs -n <namespace> -l app=<webhook-app>If the message ends with an x509: ... error, the webhook is reachable
but the TLS connection fails. It is neither a connection refused nor a
timeout, and fixing the Service changes nothing. The most frequent case is
x509: certificate signed by unknown authority: the caBundle of the
configuration does not match the certificate served. The errors
x509: certificate has expired or is not yet valid (expired certificate) and
x509: certificate is valid for X, not Y (certificate issued for a name other
than <service>.<namespace>.svc) are fixed on the webhook side, by renewing its
certificate.
Put it into practice
In the lab, no Pod can be created in the ateliers namespace any more. The controller of an old webhook was uninstalled, but the controle-ateliers webhook was left behind: it is an orphaned webhook, which calls a service that nothing backs any more. You find it from the error message of a Pod creation, then you delete it.
You then have the API server itself enforce two rules, without a webhook or a controller, in ateliers only: a MutatingAdmissionPolicy that adds the label equipe=ateliers to Pods that carry none, and a ValidatingAdmissionPolicy that rejects privileged containers, init containers included. Each policy needs its binding. The ateliers-temoin namespace is the control: neither policy must apply there.
Validation submits real Pods to the API server with --dry-run=server and looks at what it accepts, rejects or modifies. It checks that an ordinary Pod is accepted again in ateliers, that a Pod without a label comes out with equipe=ateliers while the one in ateliers-temoin gets none, and that a privileged Pod, or one whose init container is privileged, is rejected in ateliers but accepted in ateliers-temoin. You can also use --dry-run=server to test a policy without creating a Pod.
Key takeaways
- Admission Controllers are plugins that intercept API requests after authorization and before persistence in etcd.
- Mutating controllers (modify) run before validating ones (accept or reject), then the resource is written to etcd.
- Pod Security Admission is the built-in controller that enforces the Pod Security Standards, through namespace labels.
--enable-admission-pluginsadds controllers to the binary's default list.NodeRestrictionis not on it, kubeadm adds it.- ValidatingAdmissionPolicy (K8s 1.30+) and MutatingAdmissionPolicy (K8s 1.36+) form a native validation and mutation duo in CEL, with no webhook.
- Webhooks remain necessary for resource generation, signature verification and complex business logic.
- With
failurePolicy: Fail, an unreachable webhook causes the request to be rejected; withIgnore, the request goes through with no validation. - For the CKS, the focus is on PSA, VAP and MAP (native), not on Kyverno or Gatekeeper.
Test your knowledge
These questions cover the built-in controllers, webhooks and their failurePolicy, the native policies and the diagnosis of a rejection. If you hesitate on execution order or on failurePolicy, reread those two sections.
Knowledge check
Check what you have learned with this interactive quiz
How it works
- The timer starts when you click Start
- Multiple choice, true/false and short answer questions
- You can move between questions
- Detailed results are shown at the end
Starts the quiz and the timer
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: ValidatingAdmissionPolicy & MutatingAdmissionPolicy: native CEL policies (CKS)
A new full quiz with random questions
Work again only on the questions you missed