Kubernetes ships a built-in ValidatingAdmissionPolicy resource whose rules are written in CEL (Common Expression Language) and evaluated inside the API server. How does it work, and when would you pick it over an external validating admission webhook?
answer
- policy = logic, binding = scope + action
- CEL in-process, no webhook pod, no certs
- object / oldObject / request / params / namespaceObject / authorizer
- validationActions: Deny, Warn, Audit
- validates only, can't call out; mutation: MutatingAdmissionPolicy
basics
~20 sValidatingAdmissionPolicy holds CEL expressions the API server evaluates in-process on incoming objects. A ValidatingAdmissionPolicyBinding scopes it and picks the action: Deny, Warn, or Audit. No webhook means no certificates, no network hop, no availability risk. It only validates (in-tree mutation is MutatingAdmissionPolicy, GA in 1.36), and CEL cannot call out.
solid answer
~1 minA **ValidatingAdmissionPolicy** declares `matchConstraints` (which resources and verbs it applies to) and `validations` — CEL expressions over `object`, `oldObject`, `request`, `params`, `namespaceObject` and `authorizer`. A separate **ValidatingAdmissionPolicyBinding** attaches it to a scope (namespace selector, optional `paramRef` to a parameter object) and sets `validationActions`: `Deny`, `Warn`, `Audit`, or a combination such as `[Warn, Audit]` (`Deny` and `Warn` cannot be paired). Because CEL runs inside kube-apiserver there is no webhook Deployment to keep healthy, no TLS certificate to rotate, and no service that can be unreachable — the policy's own `failurePolicy` (default `Fail`) covers only CEL errors and misconfigured policies or bindings. The check costs a bounded in-process expression instead of a TLS round trip on every write. The cost is expressiveness. CEL is deliberately non-Turing-complete, sandboxed and budget-limited: it cannot query a registry, verify an image signature, or read cluster state beyond the bound `params` object and the request's namespace. And a validating policy never changes the request: in-tree mutation is the separate **MutatingAdmissionPolicy** (GA in Kubernetes 1.36), whose CEL `mutations` emit apply configurations or JSON patches. So: field-level invariants (required labels, banned fields, resource limits present, immutable spec fields) belong in ValidatingAdmissionPolicy, CEL-expressible defaulting in MutatingAdmissionPolicy; anything needing external data, signature verification, or generated side-effect resources stays in Kyverno, Gatekeeper, or a hand-written webhook. Most clusters run both.
code
yaml · 29 linesapiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata:
name: require-cpu-limits
spec:
failurePolicy: Fail
matchConstraints:
resourceRules:
- apiGroups: ["apps"]
apiVersions: ["v1"]
operations: ["CREATE", "UPDATE"]
resources: ["deployments"]
validations:
- expression: >-
object.spec.template.spec.containers.all(c,
has(c.resources) && has(c.resources.limits) && has(c.resources.limits.cpu))
message: "every container must set resources.limits.cpu"
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata:
name: require-cpu-limits-prod
spec:
policyName: require-cpu-limits
validationActions: ["Deny"]
matchResources:
namespaceSelector:
matchLabels:
env: prodgo deeper
Know that Kubernetes can enforce custom rules on objects at creation time, that ValidatingAdmissionPolicy is the built-in way to do it, and that it only rejects — it never edits.
Explain the policy/binding split, the CEL variables available, and the Deny/Warn/Audit actions, and give one concrete rule you'd express this way.
Lead with the operational argument: no webhook pod, no certificate rotation, no unreachable service to fail open or closed, lower write latency — and be precise about the class of rules that still require a webhook.
Frame it as a policy-architecture split: cheap invariants and CEL-expressible mutations in-tree and centrally versioned (MutatingAdmissionPolicy is GA from 1.36), external engines only where external data, generation or signature checks are unavoidable, with a stated version floor across the fleet.
## The problem it solves Before ValidatingAdmissionPolicy, every custom cluster rule — "pods must set resource limits", "Ingress hosts must end in our domain" — required a **validating admission webhook**: a pod you deploy, expose as a Service, serve TLS from, register with a `ValidatingWebhookConfiguration`, and keep online. Every matching API write then makes a synchronous HTTPS call to it. That is a lot of operational surface for what is often a one-line field check, and it puts your own workload on the critical path of the control plane. ## What the API does Two objects, deliberately split: **ValidatingAdmissionPolicy** — the *logic*, written once and reusable. It contains: - `matchConstraints`: resource rules (apiGroups, apiVersions, resources, operations) selecting which requests it sees. - `validations`: a list of CEL `expression`s that must evaluate to `true`, each with a `message` or `messageExpression` returned on failure. - optional `variables` (named sub-expressions), `auditAnnotations`, and `matchConditions` (CEL predicates that cheaply skip the policy). - optional `paramKind`: the type of a parameter object the expressions can read as `params`. **ValidatingAdmissionPolicyBinding** — the *scoping and enforcement decision*: which policy, which namespaces (`matchResources.namespaceSelector`), which parameter instance (`paramRef`), and `validationActions`. That split is the interesting design point: one policy, many bindings. The same "must have resource limits" policy can Deny in production namespaces and only Audit in sandbox namespaces, or read different threshold values per team through `paramRef`. ## The CEL environment Inside an expression you get: - `object` — the incoming object (null on DELETE), - `oldObject` — the existing object (null on CREATE), which makes update-only rules and immutability checks possible, - `request` — the AdmissionRequest metadata (operation, userInfo, namespace, dryRun), - `params` — the bound parameter object, - `namespaceObject` — the Namespace the incoming object belongs to (null for cluster-scoped objects), - `authorizer` — lets a policy ask "is this user allowed to do X?", which is how you write break-glass exemptions without hardcoding usernames. CEL has no loops that can run unbounded and no I/O, and evaluation runs against a per-request runtime cost budget, so a bad policy fails instead of hanging the API server. Syntax errors reject the policy when it is created or updated; type-checking results against the matched resource types are reported in the policy's `status.typeChecking`. ## Actions `validationActions` takes one or more of the following — any combination except `Deny` together with `Warn`, which would only duplicate the message: - **Deny** — request is rejected with a 4xx and the message. - **Warn** — the message is returned as a `Warning:` header, so `kubectl` prints it but the write succeeds. - **Audit** — the failure is recorded as an annotation in the API audit log only. That trio is what makes safe rollout possible: ship with `[Warn, Audit]`, watch the audit stream to find who would break, then flip to `[Deny]`. ## Choosing it versus a webhook Pick ValidatingAdmissionPolicy when the rule is a **pure function of the object being submitted** (plus a params object and its namespace). You get: no extra deployment, no cert rotation, lower latency, no chance that your policy component being down either blocks all writes or silently disables enforcement. Pick a webhook (or a policy engine that uses one) when you need to: verify an image signature or query a registry; consult other cluster resources for referential checks ("no two Ingresses may claim the same host"); generate companion resources; or reuse an existing Rego/Kyverno policy library. Mutation by itself is no longer on that list: a change CEL can express — add a label, default a field, inject a sidecar — can be a MutatingAdmissionPolicy instead of a mutating webhook. Note also that the built-in policies still run *inside* the same admission phase and cannot see the results of webhooks that run after them, so ordering-sensitive rules still need care. ## Version reality This answer assumes Kubernetes 1.37. ValidatingAdmissionPolicy has been GA (`admissionregistration.k8s.io/v1`) since 1.30; on older clusters it may be absent or switched off behind a feature gate. Its mutating counterpart, **MutatingAdmissionPolicy**, went alpha in 1.32, beta in 1.34 and GA in 1.36, where it is enabled by default. It mirrors the same split: - a `MutatingAdmissionPolicy` holds `matchConstraints` and a list of CEL `mutations`, each with a `patchType` of `ApplyConfiguration` (merged with server-side-apply semantics) or `JSONPatch`, plus a `reinvocationPolicy` of `Never` or `IfNeeded`; - a `MutatingAdmissionPolicyBinding` supplies scope and the params object. It runs in the mutating phase, before any validation, and cannot match DELETE. On a fleet that mixes versions, check each cluster before promising a design that depends on either.
- How would you let a specific break-glass identity bypass a ValidatingAdmissionPolicy without hardcoding a username?Use the `authorizer` variable in a matchCondition or validation: ask whether the requesting user is authorized on a sentinel resource, e.g. `authorizer.group('policy.example.com').resource('exemptions').check('use').allowed()`. Then grant that permission through RBAC to whoever needs the exemption. The policy stays static while the exemption is managed as an auditable RBAC binding rather than a policy edit.
- What stops someone writing a CEL expression that hangs the API server?CEL in Kubernetes is non-Turing-complete — no unbounded loops, no I/O — and every evaluation runs against a per-request runtime cost budget, so an expression that exceeds it fails rather than spinning, and the policy's failurePolicy decides whether that failure rejects the request or skips the policy. Syntax errors reject the policy at create or update time; type-check findings appear in its status.typeChecking.
A webhook is phoning an outside inspector on every delivery; ValidatingAdmissionPolicy is a checklist taped to the receiving desk — faster, always available, but it can only check what's in front of it.
- Claiming ValidatingAdmissionPolicy can mutate or default fields — it validates only; in-tree mutation is MutatingAdmissionPolicy.
- Thinking the CEL can read other objects in the cluster; it sees the request, the bound params object and the object's namespace only.
- Forgetting the binding: a policy with no ValidatingAdmissionPolicyBinding enforces nothing.
- Saying in-tree policy replaces Kyverno/Gatekeeper entirely, ignoring generation, image verification and external-data checks.
- Assuming it is available on any cluster version without checking (it is GA only from 1.30).
Assumes Kubernetes 1.37; ValidatingAdmissionPolicy GA in 1.30, MutatingAdmissionPolicy GA in 1.36 (alpha 1.32, beta 1.34), so in-tree CEL can both validate and mutate on current clusters.
context
- Q-06153Walk through what happens to a request such as 'kubectl apply -f pod.yaml' inside the Kubernetes API server, from the TLS connection to the object being stored in etcd.level: juniorimportance: must knowfreq 62%