ValidatingAdmissionPolicy (VAP) is the native Kubernetes mechanism for validating a resource at the moment the API server receives it (this step is called admission), with rules written in CEL (Common Expression Language, a small expression language), and without an external webhook (a service the API server must call over the network to reach a decision). This guide is geared toward CKS preparation (Certified Kubernetes Security Specialist): it teaches you to use VAP, but above all to choose the right mechanism (VAP, PSA, RBAC, webhook) and to diagnose a denial quickly.
Prerequisites: you can write a Pod manifest, you know the fields of a Security Context, and you have read the principle of Admission Controllers. PSA stands for Pod Security Admission, the built-in controller described in Pod Security Standards.
What you will learn
- Choose between VAP, Pod Security Admission, RBAC and webhooks
- Create policies for securityContext, hostPath and registries
- Quickly diagnose an admission denial
- Roll out a policy progressively (
Audit,Warn, thenDeny) - Add a native mutation with MutatingAdmissionPolicy
- Know the limits of VAP for the exam
Versions and availability
VAP reached GA (General Availability) in Kubernetes 1.30, which means it is stable and supported for production. Since Kubernetes 1.36 (April 2026), its counterpart MutatingAdmissionPolicy is also GA and enabled by default: Kubernetes now has a complete native validation + mutation duo, with no external webhook. The three examples, the mutation, the Audit, Warn and Deny modes, the type-checking warning and the message for a missing parameters ConfigMap were replayed, denials and outputs included, on a kind cluster running Kubernetes 1.37. Two points were taken from the official documentation without being replayed: the audit log annotation (not enabled on kind) and the "What VAP does not replace" list.
| Feature | Version | State | CKS notes |
|---|---|---|---|
| ValidatingAdmissionPolicy | 1.30+ | GA | Usable in the exam |
| MutatingAdmissionPolicy | 1.36+ | GA, enabled by default | Available natively |
Placing VAP in the curriculum avoids a common revision mistake. The official CKS curriculum, currently aligned with Kubernetes 1.35, does not name VAP, even though the feature has been GA since 1.30. What it does name are the skills VAP serves: cluster hardening, meaning access control and attack-surface reduction, and supply chain security, with control of the allowed registries. In other words, VAP is not an exam question but a way to answer one.
VAP architecture
Every request that creates or modifies an object goes through the API server in a fixed order: authentication, authorization (RBAC), then admission, before the write to etcd. VAP lives in the admission phase, like the controllers described in Admission Controllers. The diagram shows where it sits: the mutating controllers go first, then the validating controllers (VAP among them) give the verdict.
A VAP policy is made of three resources, and this separation is what bewilders people at first contact. The ValidatingAdmissionPolicy carries the logic in CEL but applies to nothing while it stands alone: declared without a binding, it is inert, and this is the most frequent trap. The ValidatingAdmissionPolicyBinding decides where and how it acts (which namespaces, in Audit, Warn or Deny mode). The parameters resource, optional, is a ConfigMap or a CRD that makes the same logic reusable with different values.
Keep the practical consequence in mind: a policy and its binding are two separate objects, applied by two kubectl apply commands, and you must check both when a rule "does nothing". Another case of a rule that "does nothing" is the delay: tested on kind with Kubernetes 1.37, a binding applied this very instant still lets the next request through, and the rule only acts one to two seconds after it. Wait a few seconds before testing.
Why VAP rather than an external webhook?
Before VAP, validating resources beyond what PSA allows required a webhook: a service the API server calls over the network to get a verdict. That meant Kyverno, Gatekeeper or in-house code, with one more component to maintain, TLS certificates to manage and an availability to watch.
VAP removes this operational complexity for simple validation cases.
| Aspect | VAP + MAP (native) | Webhooks (Kyverno, Gatekeeper) |
|---|---|---|
| Installation | Nothing to install | Deployment required |
| Performance | In-process, very fast | Network call |
| Availability | No external network dependency | SPOF if misconfigured |
| Language | CEL only | YAML, Rego, CEL |
| Mutation | GA in 1.36 (MutatingAdmissionPolicy) | Stable and mature |
| Audit | validationActions: [Audit] | Detailed reports |
When should you still choose a webhook? If you need resource generation (Kyverno creates NetworkPolicies from a template) or detailed compliance reports (PolicyReports), webhooks remain necessary. Simple mutation (adding labels, default values) now moves to native with MutatingAdmissionPolicy.
When to use VAP vs the alternatives
The key CKS question: which mechanism for which need?
Kubernetes offers several control mechanisms, and mixing them up is frequent, even among experienced professionals. This table helps you choose by goal, not by tool. To compare VAP with the external engines in detail, see VAP+MAP vs Kyverno vs Gatekeeper.
| Need | Recommended mechanism | Why |
|---|---|---|
| Enforce runAsNonRoot, drop capabilities | Pod Security Admission | Built for it, 3 ready-to-use profiles |
| Prevent a user from creating Secrets | RBAC | Access control by identity |
| Block hostPath or unauthorized registries | VAP | Content validation, not identity |
Inject a default label, add runAsNonRoot: true | MutatingAdmissionPolicy (GA in 1.36) | Declarative mutation in CEL, no webhook |
| Mutate while generating other resources (NetworkPolicy, Secret) | Kyverno | The only one offering generation |
| Require an image signature | ImagePolicyWebhook / Kyverno | VAP does not verify signatures |
| Complex business logic | External webhook | More flexibility than CEL |
Rule of thumb: if the control is about identity (who performs the action), it is RBAC. If the control is about content (what is created), it is VAP or PSA.
What VAP does not replace
VAP steps in at a precise moment of the admission chain: after authentication and RBAC authorization, on the content of the submitted object. Everything that happens before (who is speaking) or after (what travels on the network, what is signed) escapes it by construction. The list below is therefore not an inventory of gaps to fill: these are complementary layers that must coexist.
- RBAC: VAP does not control who can do what, only what is created
- Pod Security Admission: for standard security baselines, PSA is simpler
- NetworkPolicy: VAP does not filter network traffic
- Artifact signing: VAP does not verify cosign/notation signatures
- Advanced audit: VAP does not generate detailed compliance reports
Example 1: enforce a secure securityContext
This example is directly aligned with the CKS objective "Use appropriate pod security standards" of the Minimize Microservice Vulnerabilities domain. PSA already covers runAsNonRoot and allowPrivilegeEscalation with its profiles; the example is here to learn the mechanism and to show what a custom rule brings, such as requiring readOnlyRootFilesystem, which PSA does not check. The policy enforces these constraints on application containers as well as initContainers:
runAsNonRoot: trueallowPrivilegeEscalation: falsereadOnlyRootFilesystem: true
The three fields must be explicitly set: a missing securityContext does not mean "compliant", it means "not declared", and the double has() in each expression enforces that. The allContainers variable avoids copying each rule for the initContainers, which get exactly the same access to the node as an application container: a policy that reads only spec.containers lets a root initContainer through.
Two fields of the policy deserve a read before the YAML. matchConstraints designates the targeted resources, here Pods on creation and update. failurePolicy: Fail tells the API server to refuse the request when the policy cannot be evaluated, for example on an expression error; with Ignore, the request would pass unchecked. In CEL expressions, object designates the submitted resource; the "Available CEL variables" section gives the complete list.
apiVersion: admissionregistration.k8s.io/v1kind: ValidatingAdmissionPolicymetadata: name: require-secure-securitycontextspec: failurePolicy: Fail matchConstraints: resourceRules: - apiGroups: [""] apiVersions: ["v1"] operations: ["CREATE", "UPDATE"] resources: ["pods"] variables: # Application containers + initContainers (empty list if absent) - name: allContainers expression: >- object.spec.containers + (has(object.spec.initContainers) ? object.spec.initContainers : []) validations: # Every container must have runAsNonRoot - expression: | variables.allContainers.all(c, has(c.securityContext) && has(c.securityContext.runAsNonRoot) && c.securityContext.runAsNonRoot == true ) message: "All containers, initContainers included, must have runAsNonRoot: true" reason: Forbidden
# Require allowPrivilegeEscalation: false, explicitly - expression: | variables.allContainers.all(c, has(c.securityContext) && has(c.securityContext.allowPrivilegeEscalation) && c.securityContext.allowPrivilegeEscalation == false ) message: "allowPrivilegeEscalation must be explicitly false" reason: Forbidden
# Require readOnlyRootFilesystem - expression: | variables.allContainers.all(c, has(c.securityContext) && has(c.securityContext.readOnlyRootFilesystem) && c.securityContext.readOnlyRootFilesystem == true ) message: "readOnlyRootFilesystem must be true" reason: ForbiddenapiVersion: admissionregistration.k8s.io/v1kind: ValidatingAdmissionPolicyBindingmetadata: name: require-secure-securitycontext-bindingspec: policyName: require-secure-securitycontext validationActions: [Deny] matchResources: namespaceSelector: matchLabels: security: strict# Create the namespace with the label the binding expectskubectl create namespace secure-nskubectl label namespace secure-ns security=strict
# Apply the policy and the bindingkubectl apply -f secure-securitycontext-policy.yamlkubectl apply -f secure-securitycontext-binding.yaml
# Give the API server one to two seconds to pick up the bindingsleep 5
# FAILURE test: pod without securityContextkubectl run bad-pod -n secure-ns \ --image=nginx:1.30@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edbError from server (Forbidden): pods "bad-pod" is forbidden: ValidatingAdmissionPolicy'require-secure-securitycontext' with binding 'require-secure-securitycontext-binding'denied request: All containers, initContainers included, must have runAsNonRoot: trueapiVersion: v1kind: Podmetadata: name: good-pod namespace: secure-nsspec: containers: - name: nginx image: nginx:1.30@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb securityContext: runAsNonRoot: true runAsUser: 1000 allowPrivilegeEscalation: false readOnlyRootFilesystem: true# SUCCESS test: complete securityContextkubectl apply -f good-pod.yamlpod/good-pod createdTwo details of these outputs deserve a read. In Deny mode, the message cites only the first failing validation, runAsNonRoot here, even though all three fail: the other two appear only in Warn mode or in the audit log, both covered below. And an admitted Pod is not a running Pod: good-pod passes admission, then nginx fails at startup with mkdir() "/var/cache/nginx/client_temp" failed (30: Read-only file system), because the image expects a writable root. VAP judges the manifest, not the execution; making an image compatible with these constraints is the subject of the Security Context guide.
Example 2: deny hostPath volumes
hostPath volumes are a classic attack vector: they give access to the host filesystem. This policy forbids them, and its binding attaches it to the same secure-ns namespace as example 1. The !has(object.spec.volumes) at the start of the expression is not decorative: a Pod with no volume at all has no volumes field, and without this test the policy would refuse it on an evaluation error.
apiVersion: admissionregistration.k8s.io/v1kind: ValidatingAdmissionPolicymetadata: name: deny-hostpath-volumesspec: failurePolicy: Fail matchConstraints: resourceRules: - apiGroups: [""] apiVersions: ["v1"] operations: ["CREATE", "UPDATE"] resources: ["pods"] validations: - expression: | !has(object.spec.volumes) || !object.spec.volumes.exists(v, has(v.hostPath)) message: "hostPath volumes are forbidden" reason: Forbidden---apiVersion: admissionregistration.k8s.io/v1kind: ValidatingAdmissionPolicyBindingmetadata: name: deny-hostpath-volumes-bindingspec: policyName: deny-hostpath-volumes validationActions: [Deny] matchResources: namespaceSelector: matchLabels: security: strictTest: the Pod below complies with example 1, and only its volume condemns it.
apiVersion: v1kind: Podmetadata: name: hostpath-pod namespace: secure-nsspec: volumes: - name: host-vol hostPath: path: /etc containers: - name: nginx image: nginx:1.30@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb volumeMounts: - name: host-vol mountPath: /host-etc securityContext: runAsNonRoot: true runAsUser: 1000 allowPrivilegeEscalation: false readOnlyRootFilesystem: truekubectl apply -f hostpath-pod.yamlError from server (Forbidden): error when creating "hostpath-pod.yaml": pods "hostpath-pod"is forbidden: ValidatingAdmissionPolicy 'deny-hostpath-volumes' with binding'deny-hostpath-volumes-binding' denied request: hostPath volumes are forbiddenExample 3: restrict allowed registries (supply chain)
This example introduces the third component of the architecture: parameterization. The list of allowed registries does not live in the policy but in a ConfigMap, designated by the binding's paramRef and read in CEL through params. The benefit is direct: adding a registry is done with a kubectl edit configmap, without touching the validation logic or redeploying it. Note the binding's parameterNotFoundAction: Deny, which decides what happens if the ConfigMap disappears: refusing by default is the only defensible choice for a security rule, since the alternative would let everything through silently.
apiVersion: admissionregistration.k8s.io/v1kind: ValidatingAdmissionPolicymetadata: name: restrict-image-registriesspec: failurePolicy: Fail paramKind: apiVersion: v1 kind: ConfigMap matchConstraints: resourceRules: - apiGroups: [""] apiVersions: ["v1"] operations: ["CREATE", "UPDATE"] resources: ["pods"] variables: # Application containers + initContainers (empty list if absent) - name: allContainers expression: >- object.spec.containers + (has(object.spec.initContainers) ? object.spec.initContainers : []) - name: allowedRegistries expression: | params.data.allowedRegistries.split(',') validations: - expression: | variables.allContainers.all(c, variables.allowedRegistries.exists(r, c.image.startsWith(r)) ) messageExpression: | 'Image not allowed. Allowed registries: ' + params.data.allowedRegistries reason: ForbiddenapiVersion: v1kind: ConfigMapmetadata: name: allowed-registries namespace: secure-nsdata: allowedRegistries: "gcr.io/my-project/,docker.io/library/"apiVersion: admissionregistration.k8s.io/v1kind: ValidatingAdmissionPolicyBindingmetadata: name: restrict-registries-bindingspec: policyName: restrict-image-registries validationActions: [Deny] paramRef: name: allowed-registries namespace: secure-ns parameterNotFoundAction: Deny matchResources: namespaceSelector: matchLabels: security: strictTwo choices in the policy matter as much as the ConfigMap. The allContainers variable makes the rule read the initContainers in addition to the containers: without it, a Pod whose init container alone comes from a forbidden registry passes admission, even though an init container gets the same access as an application container. And each prefix in the ConfigMap ends with /: with gcr.io/my-project and no trailing slash, startsWith also accepts gcr.io/my-project-evil/app:1.0, the registry of another project whose name starts the same way. Replayed with the old prefix, the evil-pod Pod was created; with the prefix ending in /, it is refused.
A trap observed on images with no registry. A manifest that writes nginx:1.30@sha256:… is refused, because the string starts with none of the allowed prefixes, even though the image does come from Docker Hub. The same image written docker.io/library/nginx:1.30@sha256:… passes. CEL compares strings, it does not normalize image references: that is the intended effect, provided the error message says so, which is what the messageExpression does by echoing the allowed list.
The table summarizes the five Pods replayed on kind with Kubernetes 1.37, using the ConfigMap from the "Parameters" tab:
| Pod | Image | Result |
|---|---|---|
noreg-pod | nginx:1.30@sha256:… | refused |
library-pod | docker.io/library/nginx:1.30@sha256:… | created |
gcr-ok-pod | gcr.io/my-project/app:1.0 | created |
evil-pod | gcr.io/my-project-evil/app:1.0 | refused |
init-pod | init container quay.io/interdit/prep:1.0, container docker.io/library/nginx:… | refused |
The three refusals carry the same message, the one from the messageExpression:
Error from server (Forbidden): pods "noreg-pod" is forbidden: ValidatingAdmissionPolicy'restrict-image-registries' with binding 'restrict-registries-binding' denied request:Image not allowed. Allowed registries: gcr.io/my-project/,docker.io/library/Native mutation with MutatingAdmissionPolicy (GA 1.36)
Since Kubernetes 1.36, you can mutate resources with the same declarative approach as VAP, through a MutatingAdmissionPolicy (MAP). The pattern to remember: VAP validates, MAP modifies, both are written in CEL and applied through a Binding.
Mutations support two patchType values:
ApplyConfiguration, describes the partial object to merge through Server-Side Apply. Readable, robust on structured fields.JSONPatch, a list of JSON Patch operations (RFC 6902). More expressive but more fragile on missing paths.
Example: inject a default label
This example automatically adds the label team: platform to every Pod created in the map-test namespace. It is the way to apply a convention without depending on who writes the manifest.
apiVersion: admissionregistration.k8s.io/v1kind: MutatingAdmissionPolicymetadata: name: add-team-labelspec: failurePolicy: Fail reinvocationPolicy: Never matchConstraints: resourceRules: - apiGroups: [""] apiVersions: ["v1"] operations: ["CREATE"] resources: ["pods"] matchConditions: - name: only-test-namespace expression: "request.namespace == 'map-test'" 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-test# Create the target namespacekubectl create namespace map-test
# Apply the policy + the bindingkubectl apply -f add-team-label-policy.yamlkubectl apply -f add-team-label-binding.yaml
# Give the API server a few seconds to pick up the bindingsleep 5
# Run a pod without a "team" labelkubectl -n map-test run nginx --image=nginx:1.30@sha256:9bf97bd7714f5e24c1ccd545ecb9eb5435cb6d109c97cebb15e7e455e0239edb --restart=Never
# Check that MAP injected team=platformkubectl -n map-test get pod nginx -o jsonpath='{.metadata.labels}'# {"run":"nginx","team":"platform"}When to prefer MAP over a Kyverno webhook?
On a simple mutation (adding a label, setting a default value), MAP and Kyverno do the same thing, and the native option wins by removing a component to operate: nothing to deploy, no certificates or high availability to manage. As soon as the need becomes resource generation (a NetworkPolicy created with each namespace) or image signature verification, MAP cannot answer and the question no longer arises: Kyverno remains necessary. The VAP+MAP, Kyverno and Gatekeeper comparison details these criteria.
Available CEL variables
A CEL expression written in a VAP rule has access to several variables that Kubernetes injects automatically. Knowing them is the condition for writing an expression that works: without them, there is no way to query the request or the submitted resource.
| Variable | Description | Main use |
|---|---|---|
object | Incoming resource (CREATE/UPDATE) | Validate fields |
oldObject | Existing resource (UPDATE only) | Prevent certain changes |
request | Metadata (user, operation, namespace) | Conditional rules |
params | Policy parameters (ConfigMap/CRD) | Make it configurable |
namespaceObject | The resource's namespace | Check namespace labels |
Practical examples:
object.spec.containers: access the incoming pod's containersoldObject.metadata.labels: compare with the current labels on an UPDATErequest.userInfo.username: know who makes the requestparams.data.maxReplicas: read a value from the parameters ConfigMap
Common CEL expressions for the CKS
These expressions cover most of what is asked in the practical exam. Three functions come up constantly and you need to know which one to pick: all() checks that every element meets a condition (useful to enforce), exists() that at least one does (useful to forbid, prefixed with a !), and has() tests the presence of a field before accessing it. The reflex to anchor: has() protects only one level. Writing has(c.securityContext.runAsNonRoot) on a container with no securityContext triggers an evaluation error, and with failurePolicy: Fail the request is refused with an unreadable message that echoes the whole expression. Hence the double has() in the examples.
# Require runAsNonRootobject.spec.containers.all(c, has(c.securityContext) && has(c.securityContext.runAsNonRoot) && c.securityContext.runAsNonRoot == true)
# Forbid privileged (the first has() avoids the error if securityContext is absent)!object.spec.containers.exists(c, has(c.securityContext) && has(c.securityContext.privileged) && c.securityContext.privileged == true)
# Forbid hostPath (the has() covers the case of a pod with no volume)!has(object.spec.volumes) ||!object.spec.volumes.exists(v, has(v.hostPath))
# Forbid hostNetwork/hostPID/hostIPC (each field is absent when it is false)!(has(object.spec.hostNetwork) && object.spec.hostNetwork) &&!(has(object.spec.hostPID) && object.spec.hostPID) &&!(has(object.spec.hostIPC) && object.spec.hostIPC)
# Check the image prefixobject.spec.containers.all(c, c.image.startsWith('gcr.io/'))The hostNetwork case illustrates the rule on a boolean field: when it is false, it is not written into the object, and !object.spec.hostNetwork without has() then refuses every ordinary Pod. Tested on Kubernetes 1.37, a Pod that does not declare the field is rejected with expression '!object.spec.hostNetwork' resulted in error: no such key: hostNetwork. One last reflex, not to be confused with a validation: excluding the system namespaces, !request.namespace.startsWith("kube-"), is a matchCondition. Placed in validations, it would refuse every Pod in kube-* instead of ignoring it; its place is described in the "Advanced match conditions" section.
Validation actions and progressive rollout
The common mistake is to deploy a rule straight in Deny mode and break production. The validation actions (validationActions, carried by the binding) exist precisely to allow a progressive rollout: you observe first, then you refuse.
| Action | Effect | Phase |
|---|---|---|
Audit | Log only, accepts the request | Discovery |
Warn | Accepts + warning visible in kubectl | Transition |
Deny | Refuses the request | Production |
Why this progression?
- Audit: you deploy the policy with no impact. Violations are logged, and you discover which existing resources would not comply.
- Warn: developers see the warnings when they deploy. They have time to fix things before the blocking starts.
- Deny: once every workload complies, you turn on the blocking.
Recommended strategy:
# Step 1: Observe (no impact)validationActions: [Audit]
# Step 2: Alert (users see the warnings)validationActions: [Warn, Audit]
# Step 3: BlockvalidationActions: [Deny]This progression was replayed on the policy from example 1, changing only the binding, with the same Pod without a securityContext at each step. If you applied examples 2 and 3, delete their policies first: they target the same namespace and would refuse this Pod on their own account (unauthorized registry), which would hide the effect of each action.
In Audit, the Pod is created without any message on the client side, and no Event is emitted. The violation can only be read in the API server audit log, under the annotation validation.policy.admission.k8s.io/validation_failure (a point taken from the Kubernetes documentation, not replayed here). This log exists only if kube-apiserver receives --audit-policy-file and --audit-log-path, which is the case neither on kind nor on a default kubeadm cluster: without this configuration, Audit mode leaves no readable trace, and you observe nothing until you switch to Warn.
In Warn, the Pod is still created, but kubectl displays all the failing validations, one Warning: line per expression. It is the most useful mode during the transition, because developers see the complete list of what is left to fix. In Deny, finally, the request is refused on the first failing expression.
Warning: Validation failed for ValidatingAdmissionPolicy 'require-secure-securitycontext' with binding 'require-secure-securitycontext-binding': All containers, initContainers included, must have runAsNonRoot: trueWarning: Validation failed for ValidatingAdmissionPolicy 'require-secure-securitycontext' with binding 'require-secure-securitycontext-binding': allowPrivilegeEscalation must be explicitly falseWarning: Validation failed for ValidatingAdmissionPolicy 'require-secure-securitycontext' with binding 'require-secure-securitycontext-binding': readOnlyRootFilesystem must be truepod/warn-pod createdMoving from one step to the next takes a single kubectl patch on the binding, the policy does not change:
kubectl patch validatingadmissionpolicybinding require-secure-securitycontext-binding \ --type=merge -p '{"spec":{"validationActions":["Warn","Audit"]}}'Quick troubleshooting (CKS reflexes)
ValidatingAdmissionPolicy failures fall into two families that are diagnosed in opposite ways. Either nothing is blocked even though the policy should refuse, and the problem is almost always in the binding or in matchConstraints; or everything is blocked, including what should pass, and the problem is in the CEL expression.
One particularity makes these failures more bewildering than with a webhook: CEL is evaluated by the API server itself, so there is no Pod to inspect and no controller log to read. The whole diagnosis goes through the objects and through the message returned to the client.
A policy without a binding does nothing
This is the first check to make, and it is counter-intuitive: a ValidatingAdmissionPolicy alone is inert. Verified in a lab, a policy forbidding :latest images, applied without a binding, lets a :latest Pod through without a single message.
Once the ValidatingAdmissionPolicyBinding is added, the same command fails:
The pods "avec-latest" is invalid: : ValidatingAdmissionPolicy'lab-interdit-latest' with binding 'lab-interdit-latest-binding'denied request: les images en :latest sont interditesThe message names the policy and its binding, which lets you trace straight back to the rule responsible when several are in place. The double colon is not a typo, it is the real output of a validation without a reason field. The examples in this guide set reason: Forbidden, and the same refusal is then written pods "bad-pod" is forbidden: ValidatingAdmissionPolicy ...: both forms designate the same mechanism.
Diagnostic commands
These five commands run in order and each eliminates one hypothesis: does the policy exist, does its expression compile, did the refusal leave a trace, what exactly does the client see, does the namespace carry the label the binding expects. The third deserves a warning: a VAP refusal on a direct creation (kubectl run, kubectl apply) produces no Event, the error is simply returned to the caller. You will only see Events when a controller retries the creation, typically a ReplicaSet reporting FailedCreate events that contain the policy name.
# 1. List all policies and bindingskubectl get validatingadmissionpolicies,validatingadmissionpolicybindings
# 2. See the details of a policy (type-checking errors)kubectl describe validatingadmissionpolicy <name>
# 3. See recent events (only if a controller retries the creation)kubectl get events -A --sort-by=.lastTimestamp | grep -i admission
# 4. Test a manifest with verbositykubectl apply -f pod.yaml --v=8
# 5. Check whether the namespace has the right labelskubectl get namespace <ns> --show-labelsWhere does the denial come from?
A denial on creation can come from several sources. This is a frequent source of confusion: you thought VAP was blocking, but it was PSA. Or the other way round. Here is how to identify the exact source.
| Source | How to check | Typical message |
|---|---|---|
| ValidatingAdmissionPolicy | kubectl get validatingadmissionpolicies | ValidatingAdmissionPolicy 'xxx' with binding 'yyy' denied request |
| Pod Security Admission | pod-security.kubernetes.io/* label | violates PodSecurity "restricted" |
| ResourceQuota | kubectl describe quota | exceeded quota |
| LimitRange | kubectl describe limitrange | must be less than or equal to |
| RBAC | kubectl auth can-i | forbidden: User "x" cannot create |
| External webhook | kubectl get validatingwebhookconfigurations | admission webhook "xxx" denied |
Quick diagnostic tip: the error message generally contains the name of the mechanism that blocks. Read it carefully before looking any further.
Common CEL errors
These errors appear during the policy's type-checking or at runtime. They are often due to optional fields that were not tested.
| Error | Cause | Solution |
|---|---|---|
undefined field 'xxx' | Field does not exist in the type's schema (type-checking) | Fix the field name or the targeted type |
no such key: xxx | Optional field absent from the submitted object (runtime) | has() before reading it |
no params found for policy binding | Parameters ConfigMap missing, or paramRef pointing to another name or namespace, with parameterNotFoundAction: Deny | Create the ConfigMap or fix the paramRef |
type mismatch | Wrong type (string vs int) | Check the schema |
The full message of the no params found line appears at Pod creation, not at the apply of the policy. Observed by deleting the ConfigMap from example 3, then launching a Pod, with the default refusal of parameterNotFoundAction: Deny:
The pods "sans-cm" is invalid: : ValidatingAdmissionPolicy 'restrict-image-registries'with binding 'restrict-registries-binding' denied request: failed to configurebinding: no params found for policy binding with `Deny` parameterNotFoundActionType-checking example in the status, observed with a policy on Pods that reads object.spec.replicas, a field that exists only on a Deployment. The warning arrives a few seconds after the kubectl apply, and it does not prevent the policy from being created: the error is paid for at runtime, as a refusal if failurePolicy is Fail.
status: observedGeneration: 1 typeChecking: expressionWarnings: - fieldRef: spec.validations[0].expression warning: | /v1, Kind=Pod: ERROR: <input>:1:12: undefined field 'replicas' | object.spec.replicas <= 3 | ...........^What to be able to do fast in the exam
The CKS exam is timed and does not reward writing sophisticated policies. Of the six reflexes below, points 3 and 4 are the ones that cost the most time when they are missing: searching for a binding by hand or mistaking a PSA denial for a VAP denial costs several minutes on a question worth few points. Train them first.
- Recognize when an admission policy is the right lever (vs PSA, RBAC)
- Quickly read an existing ValidatingAdmissionPolicy
- Find the binding that applies a policy
- Identify the source of a denial (VAP, PSA, quota, webhook...)
- Fix a simple CEL expression (
has(),exists(),all()) - Create a basic policy in under 5 minutes
Minimal template to memorize
This skeleton contains the bare minimum for a policy to actually apply, and nothing else. Two points not to forget under pressure: the binding's policyName must match the policy name exactly, since a typo produces no error at kubectl apply and the rule stays without effect; and only validationActions: [Deny] blocks, because a binding in [Audit] or [Warn] lets the request through. The namespaceSelector assumes the target namespace does carry the label, to be checked with kubectl get ns --show-labels.
apiVersion: admissionregistration.k8s.io/v1kind: ValidatingAdmissionPolicymetadata: name: my-policyspec: failurePolicy: Fail matchConstraints: resourceRules: - apiGroups: [""] apiVersions: ["v1"] operations: ["CREATE"] resources: ["pods"] validations: - expression: "!(has(object.spec.hostNetwork) && object.spec.hostNetwork)" message: "hostNetwork forbidden"---apiVersion: admissionregistration.k8s.io/v1kind: ValidatingAdmissionPolicyBindingmetadata: name: my-policy-bindingspec: policyName: my-policy validationActions: [Deny] matchResources: namespaceSelector: matchLabels: enforce-policy: "true"Advanced match conditions
The matchConditions are evaluated before the validations and serve to set aside requests the policy must never examine. The distinction with matchConstraints matters: the latter filters by resource type, while matchConditions filter by request content in CEL, with access to request and therefore to the calling user. It is the mechanism that avoids the classic locked-cluster scenario: a policy that is too broad and refuses system Pods prevents the cluster from repairing itself, and you can no longer deploy the fix. Systematically exclude the kube-* namespaces and the system: accounts before switching to Deny.
spec: matchConditions: - name: exclude-system-namespaces expression: '!request.namespace.startsWith("kube-")' - name: exclude-system-users expression: '!request.userInfo.username.startsWith("system:")'Put it into practice
The lab starts from a namespace that accepts any image, tag included. You must make the API server refuse those that are not pinned by their digest, with a policy it evaluates itself: no webhook, no controller to keep alive. The proof is active and works both ways, an image by tag being refused while a pinned image passes. A pinned image carries @sha256: in its reference: this test is written with the same kind of string expression as the startsWith of example 3.
Key takeaways
- VAP is GA since 1.30, MAP is GA since 1.36: Kubernetes now has a native validation + mutation duo, with no webhook
- VAP does not replace PSA, RBAC or NetworkPolicy: choose the right tool depending on whether the control is about identity or content
- 3 resources: Policy + Binding + Parameter (optional), and a policy without a binding does nothing
- CEL variables:
object,oldObject,request,params,namespaceObject - Progressive rollout:
Audit, thenWarn, thenDeny, changing only the binding - Diagnosis:
kubectl get validatingadmissionpolicies,validatingadmissionpolicybindingsthendescribe(these resources have no short name,kubectl get vapreturns an error) has()before any optional field (securityContext,hostNetwork,volumes): a missing field is an error, not afalse, andfailurePolicy: Failturns that error into a refusal- For the CKS: know how to create a simple policy, restrict registries (without verifying signatures) and identify the source of a denial
Test your knowledge
The quiz covers the trade-offs of the guide rather than CEL syntax: telling VAP, PSA and RBAC apart, knowing which resource is missing when a rule has no effect, and identifying the source of a denial.
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: Kyverno, the Kubernetes policy engine in YAML and CEL
A new full quiz with random questions
Work again only on the questions you missed