Admission control is the API server's final word, and policy engines are well-organized admission webhooks paired with reporting. The lab deliberately runs three engines side by side: writing the same rule in three dialects is the fastest way to separate what's engine-specific from how Kubernetes admission actually works.

needsmake up sec

Orientation

competency 5.4 · policy engines and admission controllers

Get the admission request pipeline exact, and almost everything else in this section follows straight from it.

request ──▶ authn ──▶ authz (RBAC) ──▶ mutating admission ──▶ schema validation ──▶ validating admission ──▶ etcd
                                               │                                             │
                                    LimitRanger, sidecar and                  PSS, ValidatingAdmissionPolicy,
                                    label injection, Kyverno                  Kyverno, Gatekeeper webhooks
                                    MutatingPolicy                            (all see the mutated object)

Walk a pod through the pipeline below. The most revealing cases are the ones where a mutation quietly satisfies a validation rule downstream:

Three consequences to carry
  1. Validating policies inspect the object after mutation, so an earlier mutation can satisfy a check the developer never wrote (that's the LimitRange trap waiting in exercise 1).
  2. Admission only runs at write time. Tightening a policy never touches objects already sitting in etcd, so you need an audit or reporting sweep to catch existing offenders.
  3. Every external webhook becomes an availability dependency of the API server, and failurePolicy decides which way you fail when it breaks.

The three dialects

Kyverno · Gatekeeper · ValidatingAdmissionPolicy
AspectKyvernoGatekeeper (OPA)ValidatingAdmissionPolicy
LanguageYAML + CELRegoCEL
ObjectsValidatingPolicy / MutatingPolicy / GeneratingPolicy / ImageValidatingPolicy (CEL); ClusterPolicy / Policy (classic, read-only from 1.20)ConstraintTemplate → generated CRD → ConstraintValidatingAdmissionPolicy + …Binding
Can mutateYesAssign mutations (separate CRDs)MutatingAdmissionPolicy covers mutations on newer versions
Can generateYes (creates and syncs resources on events)NoNo
ReportingPolicyReport CRsViolation counts on the Constraint via audit sweepsNone built in
Runs asA webhook (a Deployment you must keep alive)A webhookIn-process inside the API server
Enforcement dialspec.validationActions: [Audit|Deny|Warn] · classic: validationFailureAction: Audit|EnforceenforcementAction: deny|warn|dryrunvalidationActions on the binding

Kyverno has two dialects, and starting in 1.20 only one accepts writes. The current generation is CEL-based: ValidatingPolicy, MutatingPolicy, GeneratingPolicy, ImageValidatingPolicy, and DeletingPolicy, controlled by spec.validationActions: [Audit|Deny|Warn]. It arrived in Kyverno 1.14/1.15 and is what this lab installs and exercises. The classic generation is ClusterPolicy/Policy: typed rules (validate, mutate, generate, verifyImages) with match/exclude blocks and a JMESPath-flavored pattern syntax, toggled with spec.validationFailureAction: Audit|Enforce.

Kyverno 1.20 still serves the classic API for read, list, and delete, but blocks creates and updates and no longer runs it. You'll still see classic manifests on older clusters and across most online examples, so know how to read both, and let kubectl api-resources | grep kyverno, kubectl explain, and the cluster's response to a write tell you which one you're facing. The lab's examples/kyverno/ pair uses the CEL dialect: require-resources.yaml checks that every container declares resource requests (starting in Audit mode; flip it to Deny to enforce), and add-tenant-label.yaml mutates a cost-centre label onto Deployments at admission.

Gatekeeper separates policy logic from policy instances on purpose: a ConstraintTemplate defines a parameterized Rego policy and generates a CRD, and each Constraint is an instance of that CRD binding the rule to specific resources and parameters. That split makes reusable libraries easy to share, which is why gatekeeper-library exists. In practice, whenever an exam prompt mentions "OPA", it means Rego inside Gatekeeper templates.

ValidatingAdmissionPolicy is Kubernetes-native: pure CEL, no extra controller to install, no webhook to keep healthy, paired with a Binding that sets scope and enforcement action. It's worth practicing at least once because both third-party engines increasingly compile down to it, and an exam task can hand it to you directly.

Audit → report → fix → enforce

Rolling out policy in stages beats "just apply it" every time on scenario questions: deploy in Audit mode first, inspect the reports to find every existing offender, fix or explicitly exempt them, and only then flip to Deny. Kyverno's PolicyReports and Gatekeeper's audit violations exist specifically for that middle step, mirroring PSS's warn/audit before enforce pattern in 5.3.

Kyverno by version and by field

which API you are looking at, and what each knob does

Which Kyverno is in front of you

KindAPISinceStatus
ValidatingPolicy, ImageValidatingPolicypolicies.kyverno.io/v11.14 (Apr 2025)v1 since 1.17 (Feb 2026); v1alpha1 deprecated
MutatingPolicy, GeneratingPolicy, DeletingPolicypolicies.kyverno.io/v11.15 (Jul 2025)v1 since 1.17
Namespaced* variantspolicies.kyverno.io/v1with the aboveSame policy semantics, scoped to one namespace
PolicyExceptionpolicies.kyverno.io/v11.14v1 since 1.17; the kyverno.io/v2 one is refused from 1.20
ClusterPolicy / Policy, CleanupPolicykyverno.io/v1, kyverno.io/v2the classic APIDeprecation marked 1.17 (Feb 2026), bug fixes only 1.18, deprecated 1.19 (Aug 2026), execution removed 1.20 (Nov 2026): read, list, and delete only

On Kyverno 1.19, creating a classic policy emits an admission warning and bumps kyverno_deprecated_api_requests_total. On 1.20, Kyverno's own webhook rejects the write outright ("Kyverno v1.20 removed execution of legacy kyverno.io policy types and no longer accepts create or update requests for them"), reads still warn, and the CLI refuses to load classic files. Because kubectl api-resources | grep kyverno displays both groups either way, check the running controller version and how the cluster responds to a write. Author in the CEL kinds; stay fluent enough to read classic fields when an older cluster hands them to you.

CEL-based policy fields

  • spec.matchConstraints (resourceRules[].apiGroups/apiVersions/operations/resources, plus namespaceSelector and objectSelector) and spec.matchConditions (CEL pre-filters) mirror Kubernetes' native VAP API directly. spec.variables define reusable CEL expressions once, and spec.validations[] hold expression alongside message or messageExpression.
  • spec.validationActions takes a list of Deny, Audit, or Warn (the lab patches ["Audit"] to ["Deny"]). spec.failurePolicy accepts Fail (default) or Ignore and governs evaluation errors and webhook timeouts.
  • spec.evaluation toggles admission.enabled and background.enabled independently (turning admission off makes a policy report-only), and mode: JSON lets the CLI evaluate the same policy against a Terraform plan or any arbitrary JSON payload.
  • spec.webhookConfiguration.timeoutSeconds defaults to 10 (range 1–30); Kyverno propagates it directly into the generated ValidatingWebhookConfiguration.
  • spec.autogen: setting podControllers.controllers: [deployments, statefulsets, ...] rewrites a Pod rule so it also validates pod templates at admission (the exact fix for "my policy only blocks bare pods, not Deployments"). Setting validatingAdmissionPolicy.enabled: true compiles the policy into a native VAP so the API server enforces it in-process. Keep in mind those two options are mutually exclusive: while pod-controller autogen is enabled, Kyverno skips VAP generation and logs why in the policy status.
  • Other CEL kinds: MutatingPolicy adds mutations[] with patchType: ApplyConfiguration (a server-side-apply partial object built in CEL) or JSONPatch, plus evaluation.mutateExisting.enabled to retrofit existing objects. GeneratingPolicy uses generate[].expression: generator.Apply(namespace, [objects]) or YAML template blocks, paired with evaluation.synchronize, generateExisting, and orphanDownstreamOnPolicyDelete. DeletingPolicy takes a cron schedule, conditions, and deletionPropagationPolicy.

Classic ClusterPolicy fields, still worth reading

Kyverno 1.20 won't execute these, but plenty of older clusters and reference docs still use them. Each rule pairs match.any[] / exclude.any[] (filtering by resources.kinds, namespaces, selector, and subjects) with one action: validate (pattern, anyPattern, deny.conditions, cel.expressions, podSecurity), mutate (patchStrategicMerge, patchesJson6902, targets for existing objects), generate (data or clone, synchronize), or verifyImages. Enforcement lives on each rule via validate.failureAction: Audit|Enforce (the older top-level spec.validationFailureAction, spec.webhookTimeoutSeconds, and spec.failurePolicy were deprecated in 1.13). Watch the default: it's Audit, so a copy-pasted sample policy won't block anything until you flip it. spec.background: true (default) drives background reports for existing objects, and pattern anchors work as follows: =(field) conditional, +(field) add if absent, X(field) negation, <(field) global, with wildcards "*" and "?*".

Exceptions, reports, CLI, and configuration

  • PolicyException (policies.kyverno.io/v1) pairs policyRefs[].name/kind with CEL matchConditions. It applies to both admission and background scans and shows up in reports as a skip naming the exception. Watch the controller flags: exceptions do nothing unless --enablePolicyException=true (Helm features.policyExceptions.enabled) is turned on. An optional --exceptionNamespace=<ns> (features.policyExceptions.namespace) confines where exceptions may live; without it, every exception prints a warning ("The exceptionNamespace flag is not set"). If an exemption task fails silently, check the enable flag first.
  • Reports. PolicyReport (namespaced) and ClusterPolicyReport (wgpolicyk8s.io/v1alpha2) are generated one per resource, carrying results[].result in pass|fail|warn|error|skip plus a summary. Both admission events and background scans feed them; --allowedResults=fail (1.17+) stores only failures to keep etcd lean. Note that enforced (Deny) rejections don't show up in PolicyReports because the rejected object never existed in etcd.
  • CLI. kyverno apply policy.yaml --resource pod.yaml (or --cluster) prints pass/fail per rule, and adding -o out/ dumps mutated manifests. kyverno test . executes a kyverno-test.yaml asserting expected results[].result per rule and resource, which is how you unit-test policies in CI. On 1.20, the CLI refuses to load classic policy kinds (failed to load file, quoting the webhook's removal message); 1.19 warns instead, failing if --warnings-as-errors is set.
  • Configuration. In the kyverno ConfigMap, resourceFilters ([Kind,namespace,name] triples, wildcards allowed) exclude resources from admission. excludeGroups defaults to system:serviceaccounts:kube-system,system:nodes and excludeUsernames to !system:kube-scheduler. Kyverno's own namespace is excluded by default, while kube-system isn't. The two critical webhooks are kyverno-resource-validating-webhook-cfg and kyverno-resource-mutating-webhook-cfg: if the admission controller dies and freezes cluster writes, deleting those webhook configs is the documented emergency break-glass (Kyverno recreates them on recovery), and --forceFailurePolicyIgnore switches every generated webhook to Ignore.

Gatekeeper and the native policies, field by field

constraints, mutation, audit, VAP and MAP, the decision table

Gatekeeper

  • ConstraintTemplate (templates.gatekeeper.sh/v1): spec.crd.spec.names.kind names the generated Constraint kind (like K8sRequiredLabels), spec.crd.spec.validation.openAPIV3Schema schemas its parameters, and spec.targets[].target: admission.k8s.gatekeeper.sh carries the logic. That logic is either rego with a violation[{"msg": msg, "details": {...}}] rule over input.review.object and input.parameters, or code[].engine: K8sNativeValidation with CEL validations (plus generateVAP: true to emit a native ValidatingAdmissionPolicy). If a template includes both engines, CEL takes precedence and Rego is ignored.
  • Constraint (constraints.gatekeeper.sh/v1beta1, using the template's generated kind): scope it with spec.match (kinds[].apiGroups/kinds, scope: Cluster|Namespaced|*, namespaces/excludedNamespaces supporting prefix globs like kube-*, labelSelector, namespaceSelector) and pass inputs via spec.parameters. Set spec.enforcementAction to deny (default), warn, dryrun, or scoped with scopedEnforcementActions[] picking an action per enforcement point (validation.gatekeeper.sh for the webhook, audit.gatekeeper.sh, gator.gatekeeper.sh for shift-left CI, and vap.k8s.io). The audit loop updates status.totalViolations and status.violations[] (capped at 20 by --constraint-violations-limit) every --audit-interval (60s).
  • Mutation (mutations.gatekeeper.sh/v1): four kinds handle different targets: Assign (any field under spec, like location: "spec.containers[name: *].imagePullPolicy" with parameters.assign.value and optional pathTests using MustExist/MustNotExist), AssignMetadata (labels and annotations only, optionally copying fromMetadata namespace or name), ModifySet (add or prune list items), and AssignImage (assignDomain, assignPath, assignTag). Everything except AssignMetadata requires applyTo with explicit groups, kinds, and versions (no globs). Mutations only run on CREATE and UPDATE when the mutating webhook is enabled (--operation=mutation-webhook).
  • Referential rules and expansion. Rego policies that inspect other cluster objects (data.inventory) need those kinds cached via a SyncSet (or Config.spec.sync.syncOnly). An ExpansionTemplate lets pod-level policies validate Deployments by expanding spec.template into a synthetic Pod at admission. For external lookups, a Provider (externaldata.gatekeeper.sh) points at an in-cluster service queried via external_data({"provider": ..., "keys": [...]}), which is how Ratify and the cosign provider handle image signature verification.
  • Operations. Gatekeeper installs with failurePolicy: Ignore by default (fail open). Flipping to Fail is a deliberate hardening step, typically paired with a tight timeoutSeconds and the admission.gatekeeper.sh/ignore namespace label for exemptions. In CI, gator test -f manifests/ -f policies/ checks manifests offline and exits 1 on violations, while gator verify runs a Suite of unit tests. Warnings show up in kubectl as Warning: [constraint-name] message.

Kubernetes native policies

FieldValidatingAdmissionPolicy (GA 1.30, admissionregistration.k8s.io/v1)MutatingAdmissionPolicy (GA 1.36)
matchConstraintsresourceRules[] (groups, versions, operations, resources), namespaceSelector, objectSelector, matchPolicy
matchConditionsCEL pre-filters; all must evaluate true or the policy is skipped (evaluation errors follow failurePolicy)
variablesNamed CEL expressions referenced as variables.x
validations[] / mutations[]expression, message, messageExpression, reasonpatchType: ApplyConfiguration (Object{...} partial) or JSONPatch (array of ops); reinvocationPolicy: Never|IfNeeded
auditAnnotationskey + valueExpression written straight into the API audit eventNone
paramKind + binding paramRefReads parameters from any object (ConfigMap or CRD); paramRef.parameterNotFoundAction: Allow|Deny is required
binding.validationActions[Deny], [Warn], [Audit], or [Warn, Audit] (combining Deny and Warn is rejected)n/a
CEL variablesobject (null on DELETE), oldObject (null on CREATE), request, params, namespaceObject, authorizer
failurePolicyFail (default) or Ignore on the policy, covering evaluation errors and cost-budget exhaustion

A native denial prints ValidatingAdmissionPolicy 'x' with binding 'y' denied request: <message>. Watch out for one subtle trap: CEL type errors don't reject the policy at apply time. Instead, Kubernetes writes them into status.typeChecking, so a policy with a typo in a field path gets accepted and then denies either everything or nothing depending on failurePolicy. Always check status.typeChecking right after creating one.

Webhook mechanics every engine shares

Every ValidatingWebhookConfiguration and MutatingWebhookConfiguration is driven by the same core fields: rules[] (operations, groups, versions, resources, scope), clientConfig (a Service plus caBundle, or a URL), failurePolicy (API default is Fail; Gatekeeper ships Ignore, Kyverno ships Fail), timeoutSeconds (default 10, range 1–30), sideEffects (must be None or NoneOnDryRun to run during --dry-run=server), CEL matchConditions (GA in 1.30), and namespaceSelector / objectSelector. Mutating webhooks also support reinvocationPolicy: IfNeeded so an earlier mutator can re-run if a later one changes the object, and matchPolicy: Equivalent ensures a rule matching apps/v1 also catches apps/v1beta1. Remember the ordering guarantee: mutating webhooks always run before validating ones (in an order you don't control), and validating webhooks always see the mutated result.

Which engine

NeedPickBecause
A handful of invariants, no extra components allowedValidatingAdmissionPolicy (+ MutatingAdmissionPolicy for defaults)Runs in-process with no webhook to maintain; both are GA on 1.36
Generate resources (default NetworkPolicy, quota, or RoleBinding per namespace)Kyverno GeneratingPolicyThe only engine of the three that creates downstream objects and keeps them synced
Image signature or attestation checksKyverno ImageValidatingPolicy (built-in) or Gatekeeper + external data provider (Ratify)Requires registry lookups, which native in-process policies can't do
A library of reusable, parameterized policies with typed inputs and existing-object auditsGatekeeper ConstraintTemplate + ConstraintsClean template/instance split, mature gatekeeper-library, and audit violations right on the Constraint status
Policies that inspect other cluster objectsKyverno (context, apiCall, GlobalContextEntry) or Gatekeeper with SyncSetVAP can only see params and namespaceObject
Report-then-enforce rollout with tracked per-workload exceptionsKyverno (Audit, PolicyReport, PolicyException) or Gatekeeper (dryrun/warn, audit)VAP's Audit action only annotates audit logs; it doesn't produce report objects
Enforce the exact same rules in CI before hitting a clusterKyverno CLI (kyverno test, JSON mode) or gator testBoth evaluate manifests offline; VAP has no standalone CLI
How this gets tested

Kyverno and Gatekeeper show up in separate tasks, so the choice is usually made for you; the real test is writing the right fields in whichever dialect is named. In Kyverno, check validationActions or failureAction first, because copied samples default to audit. In Gatekeeper, check enforcementAction and make sure the Constraint's kinds actually match what you're testing. For either engine, verify the denial using both the apply error text and the report or violation count, and don't forget the tenant-namespace LimitRange trap from exercise 1.

Operating policy safely

failurePolicy, exemptions, and the blast radius
  • failurePolicy. Fail blocks writes whenever the webhook is unreachable: strong security, but capable of freezing the whole cluster if your policy pods crash. Ignore lets writes through unchecked: high availability, with a bypass window during outages. Neither is universally right; it's a deliberate risk trade-off you bound with tight timeoutSeconds and a well-scoped namespaceSelector.
  • Scope your webhooks. rules (resources and operations), namespaceSelector, and objectSelector define your interception surface. Exempting kube-system is standard practice, and it's also a governance decision: it means cluster admins have an unpoliced lane.
  • Latency. Every intercepted write pays a network round trip. Broad */* wildcard rules are how an overly eager policy engine turns into a cluster-wide API slowdown.
  • Order. Mutating webhooks run in an order you don't fully control and can fire more than once under reinvocation policies, so every mutation must be idempotent.
  • Where the message goes. Your denial message lands verbatim in the developer's kubectl apply error. Write messages a stranger can act on immediately: state what failed and how to fix it.
Diagnosis, one command each
kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations
kubectl get policyreports -A                    # kyverno findings, governance-as-data
kubectl get constraints                         # gatekeeper, with violation counts
kubectl -n kyverno logs deploy/kyverno-admission-controller | tail -50
outputcaptured 2026-11-18
$ kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations
NAME                                                                                                        WEBHOOKS   AGE
validatingwebhookconfiguration.admissionregistration.k8s.io/cnpg-validating-webhook-configuration           5          5h30m
validatingwebhookconfiguration.admissionregistration.k8s.io/config.webhook.pipeline.tekton.dev              1          5h33m
validatingwebhookconfiguration.admissionregistration.k8s.io/config.webhook.triggers.tekton.dev              1          5h33m
validatingwebhookconfiguration.admissionregistration.k8s.io/crossplane-no-usages                            1          5h31m
validatingwebhookconfiguration.admissionregistration.k8s.io/externalsecret-validate                         1          5h17m
validatingwebhookconfiguration.admissionregistration.k8s.io/gatekeeper-validating-webhook-configuration     2          5h18m
validatingwebhookconfiguration.admissionregistration.k8s.io/kyverno-cel-exception-validating-webhook-cfg    1          5h18m
validatingwebhookconfiguration.admissionregistration.k8s.io/kyverno-cleanup-validating-webhook-cfg          1          5h18m
validatingwebhookconfiguration.admissionregistration.k8s.io/kyverno-exception-validating-webhook-cfg        1          5h18m
validatingwebhookconfiguration.admissionregistration.k8s.io/kyverno-global-context-validating-webhook-cfg   1          5h18m
validatingwebhookconfiguration.admissionregistration.k8s.io/kyverno-policy-validating-webhook-cfg           1          5h18m
validatingwebhookconfiguration.admissionregistration.k8s.io/kyverno-resource-validating-webhook-cfg         2          5h18m
validatingwebhookconfiguration.admissionregistration.k8s.io/kyverno-ttl-validating-webhook-cfg              1          5h18m
validatingwebhookconfiguration.admissionregistration.k8s.io/opentelemetry-operator-validation               4          5h23m
validatingwebhookconfiguration.admissionregistration.k8s.io/prometheus-kube-prometheus-admission            2          5h28m
validatingwebhookconfiguration.admissionregistration.k8s.io/secretstore-validate                            2          5h17m
validatingwebhookconfiguration.admissionregistration.k8s.io/spire-spire-controller-manager-webhook          2          5h15m
validatingwebhookconfiguration.admissionregistration.k8s.io/validation.webhook.pipeline.tekton.dev          1          5h33m
validatingwebhookconfiguration.admissionregistration.k8s.io/validation.webhook.triggers.tekton.dev          1          5h33m

NAME                                                                                                  WEBHOOKS   AGE
mutatingwebhookconfiguration.admissionregistration.k8s.io/cnpg-mutating-webhook-configuration         4          5h30m
mutatingwebhookconfiguration.admissionregistration.k8s.io/gatekeeper-mutating-webhook-configuration   1          5h18m
mutatingwebhookconfiguration.admissionregistration.k8s.io/kyverno-policy-mutating-webhook-cfg         1          5h18m
mutatingwebhookconfiguration.admissionregistration.k8s.io/kyverno-resource-mutating-webhook-cfg       1          5h18m
mutatingwebhookconfiguration.admissionregistration.k8s.io/kyverno-verify-mutating-webhook-cfg         1          5h18m
mutatingwebhookconfiguration.admissionregistration.k8s.io/opentelemetry-operator-mutation             3          5h23m
mutatingwebhookconfiguration.admissionregistration.k8s.io/prometheus-kube-prometheus-admission        1          5h28m
mutatingwebhookconfiguration.admissionregistration.k8s.io/vpa-webhook-config                          1          5h37m
mutatingwebhookconfiguration.admissionregistration.k8s.io/webhook.pipeline.tekton.dev                 1          5h33m
mutatingwebhookconfiguration.admissionregistration.k8s.io/webhook.triggers.tekton.dev                 1          5h33m
$ kubectl get policyreports -A                    # kyverno findings, governance-as-data
NAMESPACE                       NAME                                   KIND          NAME                                                         PASS   FAIL   WARN   ERROR   SKIP   AGE
argo-rollouts                   1952b422-6d06-4d6d-adca-957d6c269cb7   Deployment    argo-rollouts                                                0      2      0      0       0      5h15m
argo-rollouts                   694dc1ee-2548-4efa-8522-030edfc26627   Deployment    argo-rollouts-dashboard                                      0      2      0      0       0      5h15m
argo-rollouts                   7db78b1f-caad-4cb4-b996-a67f8420630c   ReplicaSet    argo-rollouts-dashboard-79999f8d8f                           0      1      0      0       0      5h14m
argo-rollouts                   c84caa68-f9bb-4243-8d33-7a84ec8385b4   Pod           argo-rollouts-dashboard-79999f8d8f-xmkc4                     0      1      0      0       0      5h15m
argo-rollouts                   d4a6e4d3-c524-4cda-9707-96a50b9023c7   ReplicaSet    argo-rollouts-78bf9b9d5b                                     0      1      0      0       0      5h14m
argo-rollouts                   d9a42b95-2dac-43ed-990c-8247bf9169e8   Pod           argo-rollouts-78bf9b9d5b-k75nh                               0      1      0      0       0      5h15m
argo-rollouts                   f252a2e4-1b9f-4afd-8cb4-586dd48c9048   Pod           argo-rollouts-78bf9b9d5b-9wbj2                               0      1      0      0       0      5h15m
argo                            1ec4863a-e173-400b-9acb-2632d4282178   Deployment    argo-workflows-workflow-controller                           0      2      0      0       0      5h15m
argo                            231278ea-e174-4699-bfba-704f3dc0e784   ReplicaSet    argo-workflows-workflow-controller-9b67bbc99                 0      1      0      0       0      70m
argo                            4c46e2be-2ce6-43ec-8d04-c3c89c8f8e01   ReplicaSet    argo-workflows-workflow-controller-698c7b65c4                0      1      0      0       0      71m
argo                            517d7abf-f4df-4e5d-95b2-711eb02c6d56   ReplicaSet    argo-workflows-server-5f8b6f7594                             0      1      0      0       0      5h14m
argo                            9368514e-6215-4309-9330-157cf1c1e768   Deployment    argo-workflows-server                                        0      2      0      0       0      5h15m
argo                            97b9ec88-7fa3-44a6-b807-579a6e1abdd7   ReplicaSet    argo-workflows-workflow-controller-55df46c7b                 0      1      0      0       0      5h14m
argo                            b2682b5c-e83e-499b-beab-039f48edf603   Pod           argo-workflows-workflow-controller-9b67bbc99-2x8mk           0      1      0      0       0      70m
argo                            f50d5b4f-aee1-40d4-9e5d-61776d0b85ea   Pod           argo-workflows-server-5f8b6f7594-bsv5g                       0      1      0      0       0      5h15m
argocd                          0161576c-30c7-4620-80d2-fc457492ddae   Pod           argocd-application-controller-0                              0      1      0      0       0      5h15m
argocd                          0cd82edf-80e9-4061-b5b6-c187bcc2a703   Pod           argocd-server-658c67c549-b2ncm                               0      1      0      0       0      5h15m
argocd                          2142d0d0-e40d-49ba-a63b-e11f30e0ded9   StatefulSet   argocd-application-controller                                0      1      0      0       0      5h14m
argocd                          25fad52e-c6f3-4030-9220-7425928107bc   ReplicaSet    argocd-repo-server-5dc4468bc9                                0      1      0      0       0      5h14m
$ kubectl get constraints                         # gatekeeper, with violation counts
error: the server doesn't have a resource type "constraints"
$ kubectl -n kyverno logs deploy/kyverno-admission-controller | tail -50
Defaulted container "kyverno" out of: kyverno, kyverno-pre (init)
2026-11-18T09:21:18Z TRC github.com/kyverno/kyverno/pkg/informers/health/tracker.go:101 > admission informer stream recovered logger=setup/informer-health stream=*v1beta1.PolicyException/3 v=2
2026-11-18T09:21:31Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v1 ClusterPolicy is deprecated and will be removed in a future release; migrate to ValidatingPolicy, MutatingPolicy, GeneratingPolicy or ImageValidatingPolicy (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:21:31Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v1 Policy is deprecated and will be removed in a future release; migrate to NamespacedValidatingPolicy and the other namespaced policy types (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:21:31Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v2 PolicyException is deprecated and will be removed in a future release; migrate to PolicyException (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:22:01Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v1 ClusterPolicy is deprecated and will be removed in a future release; migrate to ValidatingPolicy, MutatingPolicy, GeneratingPolicy or ImageValidatingPolicy (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:22:01Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v1 Policy is deprecated and will be removed in a future release; migrate to NamespacedValidatingPolicy and the other namespaced policy types (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:22:01Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v2 PolicyException is deprecated and will be removed in a future release; migrate to PolicyException (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:22:19Z TRC github.com/kyverno/kyverno/pkg/informers/health/tracker.go:82 > admission informer stream interrupted logger=setup/informer-health stream=*v1beta1.NamespacedValidatingPolicy/6 v=2
2026-11-18T09:22:20Z TRC github.com/kyverno/kyverno/pkg/informers/health/tracker.go:101 > admission informer stream recovered logger=setup/informer-health stream=*v1beta1.NamespacedValidatingPolicy/6 v=2
2026-11-18T09:22:31Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v1 ClusterPolicy is deprecated and will be removed in a future release; migrate to ValidatingPolicy, MutatingPolicy, GeneratingPolicy or ImageValidatingPolicy (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:22:32Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v1 Policy is deprecated and will be removed in a future release; migrate to NamespacedValidatingPolicy and the other namespaced policy types (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:22:32Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v2 PolicyException is deprecated and will be removed in a future release; migrate to PolicyException (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:23:02Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v1 ClusterPolicy is deprecated and will be removed in a future release; migrate to ValidatingPolicy, MutatingPolicy, GeneratingPolicy or ImageValidatingPolicy (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:23:02Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v1 Policy is deprecated and will be removed in a future release; migrate to NamespacedValidatingPolicy and the other namespaced policy types (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:23:02Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v2 PolicyException is deprecated and will be removed in a future release; migrate to PolicyException (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:23:32Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v1 ClusterPolicy is deprecated and will be removed in a future release; migrate to ValidatingPolicy, MutatingPolicy, GeneratingPolicy or ImageValidatingPolicy (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:23:32Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v1 Policy is deprecated and will be removed in a future release; migrate to NamespacedValidatingPolicy and the other namespaced policy types (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:23:32Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v2 PolicyException is deprecated and will be removed in a future release; migrate to PolicyException (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:24:02Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v1 ClusterPolicy is deprecated and will be removed in a future release; migrate to ValidatingPolicy, MutatingPolicy, GeneratingPolicy or ImageValidatingPolicy (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:24:02Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v1 Policy is deprecated and will be removed in a future release; migrate to NamespacedValidatingPolicy and the other namespaced policy types (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:24:02Z INF k8s.io/client-go@v0.37.1/rest/warnings.go:107 > Warning: kyverno.io/v2 PolicyException is deprecated and will be removed in a future release; migrate to PolicyException (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/ logger=klog v=0
2026-11-18T09:24:10Z TRC github.com/kyverno/kyverno/pkg/informers/health/tracker.go:82 > admission informer stream interrupted logger=setup/informer-health stream=*v1beta1.ImageValidatingPolicy/1 v=2
2026-11-18T09:24:11Z TRC github.com/kyverno/kyverno/pkg/informers/health/tracker.go:101 > admission informer stream recovered logger=setup/informer-health stream=*v1beta1.ImageValidatingPolicy/1 v=2
2026-11-18T09:24:30Z TRC github.com/kyverno/kyverno/pkg/informers/health/tracker.go:82 > admission informer stream interrupted logger=setup/informer-health stream=*v1beta1.NamespacedImageValidatingPolicy/7 v=2
2026-11-18T09:24:31Z TRC github.com/kyverno/kyverno/pkg/informers/health/tracker.go:101 > admission informer stream recovered logger=setup/informer-health stream=*v1beta1.NamespacedImageValidatingPolicy/7 v=2
… (rest of the tail omitted)

When a cluster starts rejecting everything out of the blue, suspect a policy webhook with a dead backend. The first command locates it, and failurePolicy explains why writes froze.

Exercises

tick the dot when its check passes

Dodge one classic trap first: the tenant namespaces can't demonstrate this policy at all. Their LimitRanges inject default requests during mutating admission, before any validating webhook runs. By the time Kyverno sees a pod in team-a or team-b, it already has requests. Run this drill in a fresh namespace with no LimitRange:

kubectl create ns policy-test
kubectl -n policy-test run naked --image=busybox:1.37 --restart=Never -- sleep 60   # succeeds: Audit
for i in $(seq 18); do kubectl get policyreports -n policy-test --no-headers 2>/dev/null | grep -q naked && break; sleep 5; done; echo "report after ~$((i*5))s"
kubectl get policyreports -n policy-test    # the violation is recorded instead
kubectl patch validatingpolicy require-resource-requests --type=merge \
  -p '{"spec":{"validationActions":["Deny"]}}'
kubectl -n policy-test run naked2 --image=busybox:1.37 --restart=Never -- sleep 60
outputcaptured 2026-11-18
$ kubectl create ns policy-test
namespace/policy-test created
$ kubectl -n policy-test run naked --image=busybox:1.37 --restart=Never -- sleep 60   # succeeds: Audit
pod/naked created
$ for i in $(seq 18); do kubectl get policyreports -n policy-test --no-headers 2>/dev/null | grep -q naked && break; sleep 5; done; echo "report after ~$((i*5))s"
report after ~25s
$ kubectl get policyreports -n policy-test    # the violation is recorded instead
NAME                                   KIND   NAME    PASS   FAIL   WARN   ERROR   SKIP   AGE
d9ad627a-588a-42a9-af8f-b1417a1f572d   Pod    naked   0      1      0      0       0      2s
$ kubectl patch validatingpolicy require-resource-requests --type=merge \
  -p '{"spec":{"validationActions":["Deny"]}}'
validatingpolicy.policies.kyverno.io/require-resource-requests patched
$ kubectl -n policy-test run naked2 --image=busybox:1.37 --restart=Never -- sleep 60
Error from server: admission webhook "vpol.validate.kyverno.svc-fail" denied the request: Policy require-resource-requests failed: every container must set cpu and memory requests
verify: the second pod gets rejected quoting the policy's message ("every container must set cpu and memory requests"), while the exact same pod in team-b sails right through thanks to LimitRange-injected requests. Flip the policy back to ["Audit"] when you finish.

Create a new Deployment in team-b, then read it back: kubectl -n team-b get deploy <name> -o jsonpath='{.metadata.labels.cost-centre}' prints the namespace name, stamped onto it at admission by add-cost-centre-label. Compare that against a Deployment created before the policy existed (none of the pre-existing lab Deployments have it).

verify: mutations only touch new or updated objects at admission. Retrofitting objects already in etcd is a separate Kyverno capability (mutating existing resources) that's worth knowing exists without memorizing its exact syntax.

Build the exact same rule in Rego inside that LimitRange-free namespace. Create a ConstraintTemplate named k8srequireresources whose Rego flags containers missing resource requests, then bind a Constraint targeting Pods in policy-test starting with enforcementAction: warn. Adapt the containerrequests template from open-policy-agent/gatekeeper-library rather than writing Rego from scratch, which is how real teams work.

verify: a naked pod prints a kubectl warning on creation, then gets denied once you flip to deny, and kubectl get k8srequireresources -o yaml shows the audit violations counted. You've now felt the trade-off firsthand: CEL reads like a schema, Rego reads like code; Kyverno mutates and generates, while Gatekeeper brings a mature audit loop and template library.

Write the same rule natively as a ValidatingAdmissionPolicy + Binding (CEL expression: object.spec.containers.all(c, has(c.resources.requests)), matching Pods, bound to policy-test).

verify: Kubernetes rejects the pod with your message without touching any webhook. Delete the policy and the policy-test namespace afterward so they don't cloud later exercises.

Run kubectl get validatingwebhookconfigurations,mutatingwebhookconfigurations and inspect one Kyverno entry closely: read its rules (what gets intercepted), namespaceSelector (what's exempt), and failurePolicy.

verify: you can answer "if every Kyverno pod died right now, could anyone still deploy?" directly from failurePolicy, and articulate the trade-off. Check how kube-system is handled in the selector while you're there, since exempting the control plane is itself a governance choice.

Kyverno exposes two policy APIs (classic ClusterPolicy and CEL-based ValidatingPolicy), but from 1.20 onward only the CEL API accepts writes. Older clusters and most docs still show classic YAML, so check what the cluster in front of you accepts before writing anything.

kubectl api-resources | grep -E 'kyverno'
kubectl -n kyverno get deploy -o jsonpath='{range .items[*]}{.metadata.name} {.spec.template.spec.containers[0].image}{"\n"}{end}'
kubectl apply -f - <<'EOF'
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata: { name: legacy-shape }
spec:
  validationFailureAction: Audit
  rules:
    - name: has-team-label
      match:
        any:
          - resources: { kinds: [Pod], namespaces: [default] }
      validate:
        message: "pods should carry a team label"
        pattern:
          metadata:
            labels:
              team: "?*"
EOF
kubectl apply -f - <<'EOF'
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata: { name: team-label }
spec:
  validationActions: [Audit]
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: [v1]
        operations: [CREATE, UPDATE]
        resources: [pods]
    namespaceSelector:
      matchLabels: { kubernetes.io/metadata.name: default }
  validations:
    - expression: "has(object.metadata.labels) && object.metadata.labels.?team.orValue('') != ''"
      message: "pods should carry a team label"
EOF
sleep 5
kubectl get validatingpolicy team-label
kubectl delete validatingpolicy team-label
outputcaptured 2026-11-18
$ kubectl api-resources | grep -E 'kyverno'
cleanuppolicies                                cleanpol                               kyverno.io/v2                             true         CleanupPolicy
clustercleanuppolicies                         ccleanpol                              kyverno.io/v2                             false        ClusterCleanupPolicy
clusterpolicies                                cpol                                   kyverno.io/v1                             false        ClusterPolicy
globalcontextentries                           gctxentry                              kyverno.io/v2                             false        GlobalContextEntry
policies                                       pol                                    kyverno.io/v1                             true         Policy
policyexceptions                               polex                                  kyverno.io/v2                             true         PolicyException
updaterequests                                 ur                                     kyverno.io/v2                             true         UpdateRequest
deletingpolicies                               dpol                                   policies.kyverno.io/v1                    false        DeletingPolicy
generatingpolicies                             gpol                                   policies.kyverno.io/v1                    false        GeneratingPolicy
imagevalidatingpolicies                        ivpol                                  policies.kyverno.io/v1                    false        ImageValidatingPolicy
mutatingpolicies                               mpol                                   policies.kyverno.io/v1                    false        MutatingPolicy
namespaceddeletingpolicies                     ndpol                                  policies.kyverno.io/v1                    true         NamespacedDeletingPolicy
namespacedgeneratingpolicies                   ngpol                                  policies.kyverno.io/v1                    true         NamespacedGeneratingPolicy
namespacedimagevalidatingpolicies              nivpol                                 policies.kyverno.io/v1                    true         NamespacedImageValidatingPolicy
namespacedmutatingpolicies                     nmpol                                  policies.kyverno.io/v1                    true         NamespacedMutatingPolicy
namespacedvalidatingpolicies                   nvpol                                  policies.kyverno.io/v1                    true         NamespacedValidatingPolicy
policyexceptions                                                                      policies.kyverno.io/v1                    true         PolicyException
validatingpolicies                             vpol                                   policies.kyverno.io/v1                    false        ValidatingPolicy
clusterephemeralreports                        cephr                                  reports.kyverno.io/v1                     false        ClusterEphemeralReport
ephemeralreports                               ephr                                   reports.kyverno.io/v1                     true         EphemeralReport
$ kubectl -n kyverno get deploy -o jsonpath='{range .items[*]}{.metadata.name} {.spec.template.spec.containers[0].image}{"\n"}{end}'
kyverno-admission-controller reg.kyverno.io/kyverno/kyverno:v1.20.0
kyverno-background-controller reg.kyverno.io/kyverno/background-controller:v1.20.0
kyverno-cleanup-controller reg.kyverno.io/kyverno/cleanup-controller:v1.20.0
kyverno-reports-controller reg.kyverno.io/kyverno/reports-controller:v1.20.0
$ kubectl apply -f - <<'EOF'
apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata: { name: legacy-shape }
spec:
  validationFailureAction: Audit
  rules:
    - name: has-team-label
      match:
        any:
          - resources: { kinds: [Pod], namespaces: [default] }
      validate:
        message: "pods should carry a team label"
        pattern:
          metadata:
            labels:
              team: "?*"
EOF
Warning: kyverno.io/v1 ClusterPolicy is deprecated and will be removed in a future release; migrate to ValidatingPolicy, MutatingPolicy, GeneratingPolicy or ImageValidatingPolicy (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/
Error from server: error when creating "STDIN": admission webhook "validate-policy.kyverno.svc" denied the request: kyverno.io/v1 ClusterPolicy: Kyverno v1.20 removed execution of legacy kyverno.io policy types and no longer accepts create or update requests for them; the API remains available for read, list, export, and delete. Migrate to ValidatingPolicy, MutatingPolicy, GeneratingPolicy or ImageValidatingPolicy (policies.kyverno.io), see https://kyverno.io/docs/guides/migration-to-cel/
$ kubectl apply -f - <<'EOF'
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata: { name: team-label }
spec:
  validationActions: [Audit]
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: [v1]
        operations: [CREATE, UPDATE]
        resources: [pods]
    namespaceSelector:
      matchLabels: { kubernetes.io/metadata.name: default }
  validations:
    - expression: "has(object.metadata.labels) && object.metadata.labels.?team.orValue('') != ''"
      message: "pods should carry a team label"
EOF
validatingpolicy.policies.kyverno.io/team-label created
$ sleep 5
$ kubectl get validatingpolicy team-label
NAME         AGE   READY
team-label   6s    true
$ kubectl delete validatingpolicy team-label
validatingpolicy.policies.kyverno.io "team-label" deleted
verify: api-resources still lists both groups, Kyverno's webhook blocks the classic policy and tells you the replacement kinds, and the equivalent ValidatingPolicy creates cleanly and reports READY: true. On an older Kyverno version the classic manifest would succeed (with a deprecation warning on 1.19); either way, the cluster's response tells you immediately which API to write.

A bare pod-level policy catches the pod spawned by a ReplicaSet, meaning the developer's kubectl apply exits 0 and the actual error hides in a ReplicaSet event nobody checks. Autogen moves that denial up front to the Deployment where the human is looking.

kubectl apply -f - <<'EOF'
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata: { name: require-team-label }
spec:
  # autogen is on by default, so without this the first half is already a Deployment-level deny
  autogen:
    podControllers:
      controllers: ["none"]
  validationActions: [Deny]
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["pods"]
  validations:
    - expression: "has(object.metadata.labels) && has(object.metadata.labels.team)"
      message: "every pod must carry a team label"
EOF
sleep 15
kubectl -n default create deployment unlabelled --image=nginx:1.27-alpine
sleep 20
kubectl -n default get deploy unlabelled -o jsonpath='{.status.conditions}' | jq '.[] | {type, status, reason, message}'
kubectl -n default get events --field-selector reason=FailedCreate | tail -3
kubectl -n default delete deployment unlabelled
kubectl patch validatingpolicy require-team-label --type merge -p '{"spec":{"autogen":{"podControllers":{"controllers":["deployments"]}}}}'
sleep 20
kubectl -n default create deployment unlabelled --image=nginx:1.27-alpine
kubectl -n default delete deployment unlabelled --ignore-not-found
kubectl delete validatingpolicy require-team-label
kubectl get validatingpolicy require-team-label -o jsonpath='{.spec.autogen}{"\n"}'
outputcaptured 2026-09-13
$ kubectl apply -f - <<'EOF'
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata: { name: require-team-label }
spec:
  # autogen is on by default, so without this the first half is already a Deployment-level deny
  autogen:
    podControllers:
      controllers: ["none"]
  validationActions: [Deny]
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["pods"]
  validations:
    - expression: "has(object.metadata.labels) && has(object.metadata.labels.team)"
      message: "every pod must carry a team label"
EOF
validatingpolicy.policies.kyverno.io/require-team-label created
$ sleep 15
$ kubectl -n default create deployment unlabelled --image=nginx:1.27-alpine
deployment.apps/unlabelled created
$ sleep 20
$ kubectl -n default get deploy unlabelled -o jsonpath='{.status.conditions}' | jq '.[] | {type, status, reason, message}'
{
  "type": "Progressing",
  "status": "True",
  "reason": "NewReplicaSetCreated",
  "message": "Created new replica set \"unlabelled-6896b8687b\""
}
{
  "type": "Available",
  "status": "False",
  "reason": "MinimumReplicasUnavailable",
  "message": "Deployment does not have minimum availability."
}
{
  "type": "ReplicaFailure",
  "status": "True",
  "reason": "FailedCreate",
  "message": "admission webhook \"vpol.validate.kyverno.svc-fail\" denied the request: Policy require-team-label failed: every pod must carry a team label"
}
$ kubectl -n default get events --field-selector reason=FailedCreate | tail -3
LAST SEEN   TYPE      REASON         OBJECT                             MESSAGE
10s         Warning   FailedCreate   replicaset/unlabelled-6896b8687b   Error creating: admission webhook "vpol.validate.kyverno.svc-fail" denied the request: Policy require-team-label failed: every pod must carry a team label
$ kubectl -n default delete deployment unlabelled
deployment.apps "unlabelled" deleted from default namespace
$ kubectl patch validatingpolicy require-team-label --type merge -p '{"spec":{"autogen":{"podControllers":{"controllers":["deployments"]}}}}'
validatingpolicy.policies.kyverno.io/require-team-label patched
$ sleep 20
$ kubectl -n default create deployment unlabelled --image=nginx:1.27-alpine
error: failed to create deployment: admission webhook "vpol.validate.kyverno.svc-fail" denied the request: Policy require-team-label failed: every pod must carry a team label
$ kubectl -n default delete deployment unlabelled --ignore-not-found
$ kubectl delete validatingpolicy require-team-label
validatingpolicy.policies.kyverno.io "require-team-label" deleted
$ kubectl get validatingpolicy require-team-label -o jsonpath='{.spec.autogen}{"\n"}'
Error from server (NotFound): validatingpolicies.policies.kyverno.io "require-team-label" not found
verify: with autogen off, the Deployment succeeds and its ReplicaSet fails in an event; with autogen on, kubectl create itself is blocked immediately.

Kyverno can compile a ValidatingPolicy straight into a native ValidatingAdmissionPolicy that runs in-process with zero webhook overhead. Inspect the generated policy; it's one of the clearest ways to see how native CEL admission fits together.

kubectl apply -f - <<'EOF'
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata: { name: no-latest }
spec:
  validationActions: [Deny]
  autogen:
    # pod-controller autogen is on by default, and while it is on Kyverno skips VAP generation
    podControllers: { controllers: ["none"] }
    validatingAdmissionPolicy: { enabled: true }
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["pods"]
  validations:
    - expression: "object.spec.containers.all(c, !c.image.endsWith(':latest'))"
      message: "no :latest tags"
EOF
sleep 60
kubectl get validatingadmissionpolicies
kubectl get validatingadmissionpolicybindings
kubectl get validatingadmissionpolicy -o jsonpath='{range .items[*]}{.metadata.name} {.spec.validations[*].expression}{"\n"}{end}'
kubectl get validatingpolicy no-latest -o jsonpath='{.spec.autogen}{"\n"}'
kubectl get validatingpolicy no-latest -o jsonpath='{.status.generated} {.status.conditionStatus.message}{"\n"}'
kubectl delete validatingpolicy no-latest
outputcaptured 2026-11-18
$ kubectl apply -f - <<'EOF'
apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata: { name: no-latest }
spec:
  validationActions: [Deny]
  autogen:
    # pod-controller autogen is on by default, and while it is on Kyverno skips VAP generation
    podControllers: { controllers: ["none"] }
    validatingAdmissionPolicy: { enabled: true }
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["pods"]
  validations:
    - expression: "object.spec.containers.all(c, !c.image.endsWith(':latest'))"
      message: "no :latest tags"
EOF
validatingpolicy.policies.kyverno.io/no-latest created
$ sleep 60
$ kubectl get validatingadmissionpolicies
NAME                                      VALIDATIONS   PARAMKIND   AGE
safe-upgrades.gateway.networking.k8s.io   2             <unset>     5h45m
vpol-no-latest                            1             <unset>     60s
$ kubectl get validatingadmissionpolicybindings
NAME                                      POLICYNAME                                PARAMREF   AGE
safe-upgrades.gateway.networking.k8s.io   safe-upgrades.gateway.networking.k8s.io   <unset>    5h45m
vpol-no-latest-binding                    vpol-no-latest                            <unset>    60s
$ kubectl get validatingadmissionpolicy -o jsonpath='{range .items[*]}{.metadata.name} {.spec.validations[*].expression}{"\n"}{end}'
safe-upgrades.gateway.networking.k8s.io object.spec.group != 'gateway.networking.k8s.io' || oldObject == null || ( has(object.metadata.annotations) && object.metadata.annotations.exists(k, k == 'gateway.networking.k8s.io/channel') && object.metadata.annotations['gateway.networking.k8s.io/channel'] == 'standard' ) || ( oldObject != null && has(oldObject.metadata.annotations) && oldObject.metadata.annotations.exists(k, k == 'gateway.networking.k8s.io/channel') && oldObject.metadata.annotations['gateway.networking.k8s.io/channel'] == 'experimental' ) object.spec.group != 'gateway.networking.k8s.io' || (has(object.metadata.annotations) && object.metadata.annotations.exists(k, k == 'gateway.networking.k8s.io/bundle-version') && !matches(object.metadata.annotations['gateway.networking.k8s.io/bundle-version'], 'v1.[0-6].\\d+') && !matches(object.metadata.annotations['gateway.networking.k8s.io/bundle-version'], 'v0'))
vpol-no-latest object.spec.containers.all(c, !c.image.endsWith(':latest'))
$ kubectl get validatingpolicy no-latest -o jsonpath='{.spec.autogen}{"\n"}'
{"podControllers":{"controllers":["none"]},"validatingAdmissionPolicy":{"enabled":true}}
$ kubectl get validatingpolicy no-latest -o jsonpath='{.status.generated} {.status.conditionStatus.message}{"\n"}'
true 
$ kubectl delete validatingpolicy no-latest
validatingpolicy.policies.kyverno.io "no-latest" deleted
verify: the stored spec keeps your validatingAdmissionPolicy autogen block, a matching ValidatingAdmissionPolicy and binding named vpol-no-latest appear alongside the pre-existing safe-upgrades.gateway.networking.k8s.io with your CEL expression, and status.generated reads true. If the autogen block reads back empty, the API version pruned it and nothing will be generated. If it's present yet no VAP shows up, check the status message: drop the podControllers line and it'll tell you "skip generating ValidatingAdmissionPolicy: pod controllers autogen is enabled."

"Just this once" belongs in a tracked API object, not a Slack thread. A PolicyException explicitly names the policy and the exempted workload, and the report records a skip rather than a pass so the exception stays auditable.

kubectl -n kyverno get deploy kyverno-admission-controller -o jsonpath='{.spec.template.spec.containers[0].args}' | jq
kubectl create ns policy-exception --dry-run=client -o yaml | kubectl apply -f -
kubectl apply -f - <<'EOF'
apiVersion: policies.kyverno.io/v1
kind: PolicyException
metadata: { name: legacy-job, namespace: policy-exception }
spec:
  policyRefs:
    - name: require-resource-requests
      kind: ValidatingPolicy
  matchConditions:
    - name: only-the-legacy-pod
      expression: "object.metadata.name == 'legacy'"
EOF
kubectl -n default run legacy --image=nginx:1.27-alpine --restart=Never
# the reports controller runs behind admission, so wait for the report rather than guessing a sleep
for i in $(seq 18); do kubectl -n default get policyreport -o json | jq -e '[.items[]|select(.scope.name=="legacy")]|length>0' >/dev/null && break; sleep 5; done; echo "report after ~$((i*5))s"
kubectl -n default get policyreport
kubectl -n default get policyreport -o json | jq -r '.items[] | select(.scope.name=="legacy") | .results[] | "\(.policy) \(.result)"'
kubectl -n default delete pod legacy --ignore-not-found
kubectl -n policy-exception delete policyexceptions.policies.kyverno.io legacy-job
kubectl delete ns policy-exception
outputcaptured 2026-11-18
$ kubectl -n kyverno get deploy kyverno-admission-controller -o jsonpath='{.spec.template.spec.containers[0].args}' | jq
[
  "--caSecretName=kyverno-svc.kyverno.svc.kyverno-tls-ca",
  "--tlsSecretName=kyverno-svc.kyverno.svc.kyverno-tls-pair",
  "--tlsKeyAlgorithm=RSA",
  "--backgroundServiceAccountName=system:serviceaccount:kyverno:kyverno-background-controller",
  "--reportsServiceAccountName=system:serviceaccount:kyverno:kyverno-reports-controller",
  "--servicePort=443",
  "--webhookServerPort=9443",
  "--resyncPeriod=15m",
  "--crdWatcher=false",
  "--disableMetrics=false",
  "--otelConfig=prometheus",
  "--metricsPort=8000",
  "--admissionReports=true",
  "--maxAdmissionReports=1000",
  "--autoUpdateWebhooks=true",
  "--excludeBootstrapResources=false",
  "--enableConfigMapCaching=true",
  "--controllerRuntimeMetricsAddress=:8080",
  "--enableDeferredLoading=true",
  "--dumpPayload=false",
  "--forceFailurePolicyIgnore=false",
  "--generateValidatingAdmissionPolicy=true",
  "--generateMutatingAdmissionPolicy=false",
  "--dumpPatches=false",
  "--maxAPICallResponseLength=2000000",
  "--apiCallTimeout=30s",
  "--maxGlobalContextEntries=0",
  "--loggingFormat=text",
  "--v=2",
  "--omitEvents=PolicyApplied,PolicySkipped",
  "--enablePolicyException=true",
  "--protectManagedResources=false",
  "--protectGenerationLabels=true",
  "--allowInsecureRegistry=true",
  "--registryCredentialHelpers=default,google,amazon,azure,github",
  "--enableReporting=validate,mutate,mutateExisting,imageVerify,generate"
]
$ kubectl create ns policy-exception --dry-run=client -o yaml | kubectl apply -f -
namespace/policy-exception created
$ kubectl apply -f - <<'EOF'
apiVersion: policies.kyverno.io/v1
kind: PolicyException
metadata: { name: legacy-job, namespace: policy-exception }
spec:
  policyRefs:
    - name: require-resource-requests
      kind: ValidatingPolicy
  matchConditions:
    - name: only-the-legacy-pod
      expression: "object.metadata.name == 'legacy'"
EOF
Warning: The exceptionNamespace flag is not set
policyexception.policies.kyverno.io/legacy-job created
$ kubectl -n default run legacy --image=nginx:1.27-alpine --restart=Never
pod/legacy created
$ # the reports controller runs behind admission, so wait for the report rather than guessing a sleep
$ for i in $(seq 18); do kubectl -n default get policyreport -o json | jq -e '[.items[]|select(.scope.name=="legacy")]|length>0' >/dev/null && break; sleep 5; done; echo "report after ~$((i*5))s"
report after ~25s
$ kubectl -n default get policyreport
NAME                                   KIND   NAME     PASS   FAIL   WARN   ERROR   SKIP   AGE
773aadc5-ef4a-4a3e-bdc0-b66756345fbd   Pod    legacy   0      0      0      0       1      2s
$ kubectl -n default get policyreport -o json | jq -r '.items[] | select(.scope.name=="legacy") | .results[] | "\(.policy) \(.result)"'
require-resource-requests skip
$ kubectl -n default delete pod legacy --ignore-not-found
pod "legacy" deleted from default namespace
$ kubectl -n policy-exception delete policyexceptions.policies.kyverno.io legacy-job
policyexception.policies.kyverno.io "legacy-job" deleted from policy-exception namespace
$ kubectl delete ns policy-exception
namespace "policy-exception" deleted
verify: the pod's report row shows one SKIP and zero failures, and the detail line reads require-resource-requests skip: the exception stays visible on the record instead of vanishing from compliance reports. Don't overlook the controller flags either, because --enablePolicyException=true is what makes exceptions work in the first place.

The Kyverno CLI evaluates policies against manifests right in CI, which is where a broken policy should fail first. A test file asserts the exact outcome per resource, catching regressions before a policy change ever merges.

START=$PWD   # the cd below would otherwise follow you into every later command
mkdir -p "$HOME/.local/bin"; export PATH="$HOME/.local/bin:$PATH"
URL=$(curl -s https://api.github.com/repos/kyverno/kyverno/releases/latest | jq -r '.assets[] | select(.name | startswith("kyverno-cli_") and endswith("_linux_x86_64.tar.gz")) | .browser_download_url'); echo "$URL"
rm -rf /tmp/kyverno-cli && mkdir -p /tmp/kyverno-cli && curl -sL "$URL" | tar xz -C /tmp/kyverno-cli && install /tmp/kyverno-cli/kyverno "$HOME/.local/bin/"
kyverno version | head -2
rm -rf /tmp/kyverno-test && mkdir -p /tmp/kyverno-test && cd /tmp/kyverno-test
cp "$START"/examples/kyverno/require-resources.yaml policy.yaml   # START is the repo root you ran this from
cat > good-pod.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata: { name: good, namespace: default }
spec:
  containers:
    - name: c
      image: nginx:1.27-alpine
      resources:
        requests: { cpu: 25m, memory: 32Mi }
EOF
cat > bad-pod.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata: { name: bad, namespace: default }
spec:
  containers:
    - name: c
      image: nginx:1.27-alpine
EOF
kyverno apply policy.yaml --resource good-pod.yaml --resource bad-pod.yaml
cat > kyverno-test.yaml <<'EOF'
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata: { name: require-resources }
policies: [policy.yaml]
resources: [good-pod.yaml, bad-pod.yaml]
results:
  - policy: require-resource-requests
    resources: [good]
    kind: Pod
    result: pass
  - policy: require-resource-requests
    resources: [bad]
    kind: Pod
    result: fail
EOF
kyverno test .
cd "$START"
outputcaptured 2026-11-18
$ START=$PWD   # the cd below would otherwise follow you into every later command
$ mkdir -p "$HOME/.local/bin"; export PATH="$HOME/.local/bin:$PATH"
$ URL=$(curl -s https://api.github.com/repos/kyverno/kyverno/releases/latest | jq -r '.assets[] | select(.name | startswith("kyverno-cli_") and endswith("_linux_x86_64.tar.gz")) | .browser_download_url'); echo "$URL"
https://github.com/kyverno/kyverno/releases/download/v1.20.0/kyverno-cli_v1.20.0_linux_x86_64.tar.gz
$ rm -rf /tmp/kyverno-cli && mkdir -p /tmp/kyverno-cli && curl -sL "$URL" | tar xz -C /tmp/kyverno-cli && install /tmp/kyverno-cli/kyverno "$HOME/.local/bin/"
$ kyverno version | head -2
Version: v1.20.0
Time: 2026-11-11T12:42:56Z
$ rm -rf /tmp/kyverno-test && mkdir -p /tmp/kyverno-test && cd /tmp/kyverno-test
$ cp "$START"/examples/kyverno/require-resources.yaml policy.yaml   # START is the repo root you ran this from
$ cat > good-pod.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata: { name: good, namespace: default }
spec:
  containers:
    - name: c
      image: nginx:1.27-alpine
      resources:
        requests: { cpu: 25m, memory: 32Mi }
EOF
$ cat > bad-pod.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata: { name: bad, namespace: default }
spec:
  containers:
    - name: c
      image: nginx:1.27-alpine
EOF
$ kyverno apply policy.yaml --resource good-pod.yaml --resource bad-pod.yaml

Applying 1 policy rule(s) to 2 resource(s)...
policy require-resource-requests -> resource default/Pod/bad failed:
1 - validation every container must set cpu and memory requests

pass: 1, fail: 1, warn: 0, error: 0, skip: 0 
$ cat > kyverno-test.yaml <<'EOF'
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata: { name: require-resources }
policies: [policy.yaml]
resources: [good-pod.yaml, bad-pod.yaml]
results:
  - policy: require-resource-requests
    resources: [good]
    kind: Pod
    result: pass
  - policy: require-resource-requests
    resources: [bad]
    kind: Pod
    result: fail
EOF
$ kyverno test .
Loading test require-resources ( kyverno-test.yaml ) ...
  Loading values/variables ...
  Loading policies ...
  Loading resources ...
  Loading exceptions ...
  Applying 1 policy to 2 resources with 0 exceptions ...
  Checking results ...

│────│───────────────────────────│────────────│─────────────────────│────────│────────│
│ ID │ POLICY                    │ RULE       │ RESOURCE            │ RESULT │ REASON │
│────│───────────────────────────│────────────│─────────────────────│────────│────────│
│ 1  │ require-resource-requests │ validation │ v1/Pod/default/good │ Pass   │ Ok     │
│ 2  │ require-resource-requests │ validation │ v1/Pod/default/bad  │ Pass   │ Ok     │
│────│───────────────────────────│────────────│─────────────────────│────────│────────│


Test Summary: 2 tests passed and 0 tests failed
$ cd "$START"
verify: kyverno apply passes the compliant pod and fails the naked one, and kyverno test confirms both expectations passed.

Gatekeeper's scoped enforcement lets a single Constraint behave differently at admission and during audit sweeps. Printing a warning to the developer typing in their terminal while logging a violation for compliance reports is a practical rollout strategy, not a half-measure.

kubectl apply -f - <<'EOF'
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata: { name: k8srequiredlabels }
spec:
  crd:
    spec:
      names: { kind: K8sRequiredLabels }
      validation:
        openAPIV3Schema:
          type: object
          properties:
            labels: { type: array, items: { type: string } }
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8srequiredlabels
        violation[{"msg": msg}] {
          required := input.parameters.labels[_]
          not input.review.object.metadata.labels[required]
          msg := sprintf("missing required label: %v", [required])
        }
EOF
sleep 20
kubectl apply -f - <<'EOF'
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata: { name: pods-need-owner }
spec:
  enforcementAction: scoped
  scopedEnforcementActions:
    - action: warn
      enforcementPoints: [{ name: validation.gatekeeper.sh }]
    - action: deny
      enforcementPoints: [{ name: audit.gatekeeper.sh }]
  match:
    kinds:
      - { apiGroups: [""], kinds: [Pod] }
    namespaces: [default]
  parameters:
    labels: [owner]
EOF
sleep 30
kubectl -n default run scoped-demo --image=nginx:1.27-alpine --restart=Never
sleep 90
kubectl get k8srequiredlabels pods-need-owner -o jsonpath='{.status.violations}' | jq
kubectl -n default delete pod scoped-demo --ignore-not-found
kubectl delete k8srequiredlabels pods-need-owner
kubectl delete constrainttemplate k8srequiredlabels
outputcaptured 2026-09-12
$ kubectl apply -f - <<'EOF'
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata: { name: k8srequiredlabels }
spec:
  crd:
    spec:
      names: { kind: K8sRequiredLabels }
      validation:
        openAPIV3Schema:
          type: object
          properties:
            labels: { type: array, items: { type: string } }
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8srequiredlabels
        violation[{"msg": msg}] {
          required := input.parameters.labels[_]
          not input.review.object.metadata.labels[required]
          msg := sprintf("missing required label: %v", [required])
        }
EOF
constrainttemplate.templates.gatekeeper.sh/k8srequiredlabels created
$ sleep 20
$ kubectl apply -f - <<'EOF'
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata: { name: pods-need-owner }
spec:
  enforcementAction: scoped
  scopedEnforcementActions:
    - action: warn
      enforcementPoints: [{ name: validation.gatekeeper.sh }]
    - action: deny
      enforcementPoints: [{ name: audit.gatekeeper.sh }]
  match:
    kinds:
      - { apiGroups: [""], kinds: [Pod] }
    namespaces: [default]
  parameters:
    labels: [owner]
EOF
k8srequiredlabels.constraints.gatekeeper.sh/pods-need-owner created
$ sleep 30
$ kubectl -n default run scoped-demo --image=nginx:1.27-alpine --restart=Never
Warning: [pods-need-owner] missing required label: owner
pod/scoped-demo created
$ sleep 90
$ kubectl get k8srequiredlabels pods-need-owner -o jsonpath='{.status.violations}' | jq
[
  {
    "enforcementAction": "scoped",
    "enforcementActions": [
      "deny"
    ],
    "group": "",
    "kind": "Pod",
    "message": "missing required label: owner",
    "name": "signed-86hrq-pod",
    "namespace": "default",
    "version": "v1"
  },
  {
    "enforcementAction": "scoped",
    "enforcementActions": [
      "deny"
    ],
    "group": "",
    "kind": "Pod",
    "message": "missing required label: owner",
    "name": "scoped-demo",
    "namespace": "default",
    "version": "v1"
  }
]
$ kubectl -n default delete pod scoped-demo --ignore-not-found
pod "scoped-demo" deleted from default namespace
$ kubectl delete k8srequiredlabels pods-need-owner
k8srequiredlabels.constraints.gatekeeper.sh "pods-need-owner" deleted
$ kubectl delete constrainttemplate k8srequiredlabels
constrainttemplate.templates.gatekeeper.sh "k8srequiredlabels" deleted
verify: kubectl creates the pod while printing your warning, and the Constraint's audit status records it as a violation.

Gatekeeper can mutate objects on the way in, and which kind you pick decides whether it stomps on values a developer set intentionally. AssignMetadata only fills in a label when it's missing, whereas Assign needs a pathTests guard to avoid overwriting. Mutating blindly without either is how a platform team quietly breaks deployments.

# Assign refuses to touch metadata; labels and annotations are AssignMetadata's job,
# and it only ever fills in a value that is absent, so no pathTests condition is needed
kubectl apply -f - <<'EOF'
apiVersion: mutations.gatekeeper.sh/v1
kind: AssignMetadata
metadata: { name: default-owner-label }
spec:
  match:
    scope: Namespaced
    namespaces: [default]
    kinds:
      - { apiGroups: ["*"], kinds: [Pod] }
  location: "metadata.labels.owner"
  parameters:
    assign:
      value: platform
EOF
sleep 30
kubectl -n default run mutated --image=nginx:1.27-alpine --restart=Never
kubectl -n default get pod mutated -o jsonpath='{.metadata.labels.owner}{"\n"}'
kubectl -n default run untouched --image=nginx:1.27-alpine --restart=Never --labels=owner=team-a
kubectl -n default get pod untouched -o jsonpath='{.metadata.labels.owner}{"\n"}'
kubectl -n default delete pod mutated untouched --ignore-not-found
kubectl delete assignmetadata default-owner-label
outputcaptured 2026-09-13
$ # Assign refuses to touch metadata; labels and annotations are AssignMetadata's job,
$ # and it only ever fills in a value that is absent, so no pathTests condition is needed
$ kubectl apply -f - <<'EOF'
apiVersion: mutations.gatekeeper.sh/v1
kind: AssignMetadata
metadata: { name: default-owner-label }
spec:
  match:
    scope: Namespaced
    namespaces: [default]
    kinds:
      - { apiGroups: ["*"], kinds: [Pod] }
  location: "metadata.labels.owner"
  parameters:
    assign:
      value: platform
EOF
assignmetadata.mutations.gatekeeper.sh/default-owner-label created
$ sleep 30
$ kubectl -n default run mutated --image=nginx:1.27-alpine --restart=Never
pod/mutated created
$ kubectl -n default get pod mutated -o jsonpath='{.metadata.labels.owner}{"\n"}'
platform
$ kubectl -n default run untouched --image=nginx:1.27-alpine --restart=Never --labels=owner=team-a
pod/untouched created
$ kubectl -n default get pod untouched -o jsonpath='{.metadata.labels.owner}{"\n"}'
team-a
$ kubectl -n default delete pod mutated untouched --ignore-not-found
pod "mutated" deleted from default namespace
pod "untouched" deleted from default namespace
$ kubectl delete assignmetadata default-owner-label
assignmetadata.mutations.gatekeeper.sh "default-owner-label" deleted
verify: the pod without an owner label gets platform, while the pod with owner=team-a keeps team-a. Notice the kind distinction: Assign won't touch metadata at all, so labels and annotations belong to AssignMetadata, which only populates missing values by design (the line between a helpful default and a forced override). Also skip imagePullPolicy for "mutate if unset" drills: the API server defaults it before any mutating webhook runs, so the condition never triggers.

gator test runs Gatekeeper constraints against manifests straight from a laptop or build runner. Same rules, same answers, no cluster needed, which is what makes policy-as-code actually reviewable.

START=$PWD   # the cd below would otherwise follow you into every later command
mkdir -p "$HOME/.local/bin"; export PATH="$HOME/.local/bin:$PATH"
URL=$(curl -s https://api.github.com/repos/open-policy-agent/gatekeeper/releases/latest | jq -r '.assets[] | select(.name | startswith("gator-") and endswith("-linux-amd64.tar.gz")) | .browser_download_url'); echo "$URL"
rm -rf /tmp/gator-bin && mkdir -p /tmp/gator-bin && curl -sL "$URL" | tar xz -C /tmp/gator-bin && install /tmp/gator-bin/gator "$HOME/.local/bin/"
gator version
rm -rf /tmp/gator-ci && mkdir -p /tmp/gator-ci/policies /tmp/gator-ci/manifests && cd /tmp/gator-ci
cat > policies/template.yaml <<'EOF'
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata: { name: k8sdenylatest }
spec:
  crd:
    spec:
      names: { kind: K8sDenyLatest }
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8sdenylatest
        violation[{"msg": msg}] {
          c := input.review.object.spec.containers[_]
          endswith(c.image, ":latest")
          msg := sprintf("image uses the latest tag: %v", [c.image])
        }
EOF
cat > policies/constraint.yaml <<'EOF'
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sDenyLatest
metadata: { name: no-latest-anywhere }
spec:
  match:
    kinds:
      - { apiGroups: [""], kinds: [Pod] }
EOF
cat > manifests/pods.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata: { name: pinned }
spec:
  containers: [{ name: c, image: nginx:1.27-alpine }]
---
apiVersion: v1
kind: Pod
metadata: { name: floating }
spec:
  containers: [{ name: c, image: nginx:latest }]
EOF
gator test -f manifests/ -f policies/; echo "exit code: $?"
cd "$START"
outputcaptured 2026-09-12
$ START=$PWD   # the cd below would otherwise follow you into every later command
$ mkdir -p "$HOME/.local/bin"; export PATH="$HOME/.local/bin:$PATH"
$ URL=$(curl -s https://api.github.com/repos/open-policy-agent/gatekeeper/releases/latest | jq -r '.assets[] | select(.name | startswith("gator-") and endswith("-linux-amd64.tar.gz")) | .browser_download_url'); echo "$URL"
https://github.com/open-policy-agent/gatekeeper/releases/download/v3.23.1/gator-v3.23.1-linux-amd64.tar.gz
$ rm -rf /tmp/gator-bin && mkdir -p /tmp/gator-bin && curl -sL "$URL" | tar xz -C /tmp/gator-bin && install /tmp/gator-bin/gator "$HOME/.local/bin/"
$ gator version
 ::::::::      :::     :::::::::::  ::::::::  :::::::::
:+:    :+:   :+: :+:       :+:     :+:    :+: :+:    :+:
+:+         +:+   +:+      +:+     +:+    +:+ +:+    +:+
:#:        +#++:++#++:     +#+     +#+    +:+ +#++:++#:
+#+   +#+# +#+     +#+     +#+     +#+    +#+ +#+    +#+
#+#    #+# #+#     #+#     #+#     #+#    #+# #+#    #+#
 ########  ###     ###     ###      ########  ###    ###
gator: gator is a suite of authorship tools for Gatekeeper

GitVersion:    v3.23.1+dirty
GitCommit:     2d0b6ad97cf3a8b8436a00a1f4b07b3a56b92ca0
GitTreeState:  dirty
BuildDate:     2026-08-27T21:26:44
GoVersion:     go1.26.0
Compiler:      gc
Platform:      linux/amd64
$ rm -rf /tmp/gator-ci && mkdir -p /tmp/gator-ci/policies /tmp/gator-ci/manifests && cd /tmp/gator-ci
$ cat > policies/template.yaml <<'EOF'
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata: { name: k8sdenylatest }
spec:
  crd:
    spec:
      names: { kind: K8sDenyLatest }
  targets:
    - target: admission.k8s.gatekeeper.sh
      rego: |
        package k8sdenylatest
        violation[{"msg": msg}] {
          c := input.review.object.spec.containers[_]
          endswith(c.image, ":latest")
          msg := sprintf("image uses the latest tag: %v", [c.image])
        }
EOF
$ cat > policies/constraint.yaml <<'EOF'
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sDenyLatest
metadata: { name: no-latest-anywhere }
spec:
  match:
    kinds:
      - { apiGroups: [""], kinds: [Pod] }
EOF
$ cat > manifests/pods.yaml <<'EOF'
apiVersion: v1
kind: Pod
metadata: { name: pinned }
spec:
  containers: [{ name: c, image: nginx:1.27-alpine }]
---
apiVersion: v1
kind: Pod
metadata: { name: floating }
spec:
  containers: [{ name: c, image: nginx:latest }]
EOF
$ gator test -f manifests/ -f policies/; echo "exit code: $?"
v1/Pod floating: ["no-latest-anywhere"] Message: "image uses the latest tag: nginx:latest"
exit code: 1
$ cd "$START"
verify: the floating :latest pod triggers a violation with your message and exits 1, while the pinned pod passes cleanly.

A ValidatingAdmissionPolicy with a typo in a field path won't fail at apply time; it fails during runtime evaluation, where failurePolicy decides the fallout. Fortunately, the API server type-checks expressions up front and writes any warnings straight into status.typeChecking.

kubectl apply -f - <<'EOF'
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata: { name: typo-policy }
spec:
  failurePolicy: Fail
  matchConstraints:
    resourceRules:
      - apiGroups: ["apps"]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["deployments"]
  validations:
    - expression: "object.spec.replicaCount <= 10"
      message: "at most ten replicas"
EOF
sleep 10
kubectl get validatingadmissionpolicy typo-policy -o jsonpath='{.status.typeChecking}' | jq
kubectl apply -f - <<'EOF'
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata: { name: typo-policy-binding }
spec:
  policyName: typo-policy
  validationActions: [Deny]
  matchResources:
    namespaceSelector:
      matchLabels: { kubernetes.io/metadata.name: default }
EOF
sleep 10
kubectl -n default create deployment typo-test --image=nginx:1.27-alpine
kubectl patch validatingadmissionpolicy typo-policy --type merge -p '{"spec":{"failurePolicy":"Ignore"}}'
sleep 10
kubectl -n default create deployment typo-test --image=nginx:1.27-alpine
kubectl -n default delete deployment typo-test --ignore-not-found
kubectl delete validatingadmissionpolicybinding typo-policy-binding
kubectl delete validatingadmissionpolicy typo-policy
outputcaptured 2026-09-12
$ kubectl apply -f - <<'EOF'
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicy
metadata: { name: typo-policy }
spec:
  failurePolicy: Fail
  matchConstraints:
    resourceRules:
      - apiGroups: ["apps"]
        apiVersions: ["v1"]
        operations: ["CREATE", "UPDATE"]
        resources: ["deployments"]
  validations:
    - expression: "object.spec.replicaCount <= 10"
      message: "at most ten replicas"
EOF
validatingadmissionpolicy.admissionregistration.k8s.io/typo-policy created
$ sleep 10
$ kubectl get validatingadmissionpolicy typo-policy -o jsonpath='{.status.typeChecking}' | jq
{
  "expressionWarnings": [
    {
      "fieldRef": "spec.validations[0].expression",
      "warning": "apps/v1, Kind=Deployment: ERROR: <input>:1:12: undefined field 'replicaCount'\n | object.spec.replicaCount <= 10\n | ...........^\n"
    }
  ]
}
$ kubectl apply -f - <<'EOF'
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingAdmissionPolicyBinding
metadata: { name: typo-policy-binding }
spec:
  policyName: typo-policy
  validationActions: [Deny]
  matchResources:
    namespaceSelector:
      matchLabels: { kubernetes.io/metadata.name: default }
EOF
validatingadmissionpolicybinding.admissionregistration.k8s.io/typo-policy-binding created
$ sleep 10
$ kubectl -n default create deployment typo-test --image=nginx:1.27-alpine
error: failed to create deployment: deployments.apps "typo-test" is forbidden: ValidatingAdmissionPolicy 'typo-policy' with binding 'typo-policy-binding' denied request: expression 'object.spec.replicaCount <= 10' resulted in error: no such key: replicaCount
$ kubectl patch validatingadmissionpolicy typo-policy --type merge -p '{"spec":{"failurePolicy":"Ignore"}}'
validatingadmissionpolicy.admissionregistration.k8s.io/typo-policy patched
$ sleep 10
$ kubectl -n default create deployment typo-test --image=nginx:1.27-alpine
deployment.apps/typo-test created
$ kubectl -n default delete deployment typo-test --ignore-not-found
deployment.apps "typo-test" deleted from default namespace
$ kubectl delete validatingadmissionpolicybinding typo-policy-binding
validatingadmissionpolicybinding.admissionregistration.k8s.io "typo-policy-binding" deleted
$ kubectl delete validatingadmissionpolicy typo-policy
validatingadmissionpolicy.admissionregistration.k8s.io "typo-policy" deleted
verify: status.typeChecking calls out the nonexistent field, the Deployment gets blocked under Fail, and the exact same broken policy waves everything through under Ignore. Make reading status.typeChecking a habit before trusting a brand-new VAP.

MutatingAdmissionPolicy does for defaults what VAP did for validation: pure CEL inside the API server with no external controller to babysit. Stamp a label with an apply configuration and watch it show up on a pod nobody patched.

kubectl api-resources | grep -i mutatingadmissionpolicy
kubectl apply -f - <<'EOF'
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingAdmissionPolicy
metadata: { name: add-platform-label }
spec:
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE"]
        resources: ["pods"]
  failurePolicy: Fail
  reinvocationPolicy: Never
  mutations:
    - patchType: ApplyConfiguration
      applyConfiguration:
        expression: |
          Object{ metadata: Object.metadata{ labels: {"managed-by": "platform"} } }
---
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingAdmissionPolicyBinding
metadata: { name: add-platform-label-binding }
spec:
  policyName: add-platform-label
  matchResources:
    namespaceSelector:
      matchLabels: { kubernetes.io/metadata.name: default }
EOF
sleep 15
kubectl -n default run mutated-native --image=nginx:1.27-alpine --restart=Never --overrides='{"spec":{"containers":[{"name":"mutated-native","image":"nginx:1.27-alpine","resources":{"requests":{"cpu":"25m","memory":"32Mi"}}}]}}'
kubectl -n default get pod mutated-native -o jsonpath='{.metadata.labels}{"\n"}'
kubectl -n default delete pod mutated-native --ignore-not-found
kubectl delete mutatingadmissionpolicybinding add-platform-label-binding
kubectl delete mutatingadmissionpolicy add-platform-label
outputcaptured 2026-09-12
$ kubectl api-resources | grep -i mutatingadmissionpolicy
mutatingadmissionpolicies                                                             admissionregistration.k8s.io/v1           false        MutatingAdmissionPolicy
mutatingadmissionpolicybindings                                                       admissionregistration.k8s.io/v1           false        MutatingAdmissionPolicyBinding
$ kubectl apply -f - <<'EOF'
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingAdmissionPolicy
metadata: { name: add-platform-label }
spec:
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        operations: ["CREATE"]
        resources: ["pods"]
  failurePolicy: Fail
  reinvocationPolicy: Never
  mutations:
    - patchType: ApplyConfiguration
      applyConfiguration:
        expression: |
          Object{ metadata: Object.metadata{ labels: {"managed-by": "platform"} } }
---
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingAdmissionPolicyBinding
metadata: { name: add-platform-label-binding }
spec:
  policyName: add-platform-label
  matchResources:
    namespaceSelector:
      matchLabels: { kubernetes.io/metadata.name: default }
EOF
mutatingadmissionpolicy.admissionregistration.k8s.io/add-platform-label created
mutatingadmissionpolicybinding.admissionregistration.k8s.io/add-platform-label-binding created
$ sleep 15
$ kubectl -n default run mutated-native --image=nginx:1.27-alpine --restart=Never --overrides='{"spec":{"containers":[{"name":"mutated-native","image":"nginx:1.27-alpine","resources":{"requests":{"cpu":"25m","memory":"32Mi"}}}]}}'
pod/mutated-native created
$ kubectl -n default get pod mutated-native -o jsonpath='{.metadata.labels}{"\n"}'
{"managed-by":"platform","run":"mutated-native","topology.kubernetes.io/zone":"zone-b"}
$ kubectl -n default delete pod mutated-native --ignore-not-found
pod "mutated-native" deleted from default namespace
$ kubectl delete mutatingadmissionpolicybinding add-platform-label-binding
mutatingadmissionpolicybinding.admissionregistration.k8s.io "add-platform-label-binding" deleted
$ kubectl delete mutatingadmissionpolicy add-platform-label
mutatingadmissionpolicy.admissionregistration.k8s.io "add-platform-label" deleted
verify: the pod gets managed-by: platform with zero mutating webhooks involved. If an older exam cluster doesn't serve this API yet, state that directly and note the feature gate; that's the right answer there.

Self-check

answer before opening
A "require requests" policy never fires in a tenant namespace. Why?

The namespace's LimitRange injects default requests during mutating admission, before validating webhooks execute, so the pod Kyverno sees already complies. Admission ordering (mutate first, then validate) explains this completely, and it applies to every defaulting mechanism.

failurePolicy: Fail versus Ignore: argue both, then say what bounds the risk.

Fail prevents unvalidated writes from sneaking past, at the cost of blocking cluster writes if the webhook goes down (a policy outage becomes a cluster outage). Ignore keeps deployments moving during an outage, at the cost of a policy bypass window. Bound the blast radius with a tight namespaceSelector, low timeoutSeconds, system-namespace exemptions, and enough controller replicas that the webhook isn't a single point of failure.

You tighten a policy to Deny. What happens to the workloads that already violate it?

Nothing right away, because admission only checks writes. Existing pods keep running until their next write (a rollout, scale event, or node eviction), and then fail unexpectedly, often at 3 a.m. That's why you follow Audit → report → fix → Enforce and clear the reports before flipping the dial.

Which engine would you pick to also create a default NetworkPolicy in every new namespace?

Kyverno. Resource generation is first-class there: a GeneratingPolicy (or a classic generate rule on older clusters) creates downstream objects and keeps them synced. Gatekeeper validates and mutates but doesn't generate, and ValidatingAdmissionPolicy only validates. Match the engine's capabilities to the requirement.

Why might a platform team prefer ValidatingAdmissionPolicy for a simple rule?

Zero extra controllers, zero webhooks, zero availability dependencies, and no version skew: the API server runs CEL right in-process. The trade-off is a narrower feature set (no generation, no built-in reports, and no mutation on older Kubernetes releases), making it ideal for crisp invariants rather than a full governance suite.

A Kyverno ValidatingPolicy denies bare pods but a Deployment with the same violating template is admitted. Field?

Set spec.autogen.podControllers.controllers to include deployments (along with statefulsets, daemonsets, jobs, and cronjobs as needed). Autogen rewrites your Pod rule to validate controller spec.template blocks directly. Without it, the Deployment gets admitted and its pods fail silently one layer down on the ReplicaSet (the same indirection as PSS). Remember that pod-controller autogen and autogen.validatingAdmissionPolicy are mutually exclusive.

Which Kyverno controller flag must be on before a PolicyException has any effect, and how does the report show an applied exception?

Only --enablePolicyException=true is mandatory. The companion flag, --exceptionNamespace=<namespace>, is optional: when set, only exceptions inside that namespace take effect; when omitted (as in this lab), exceptions work from any namespace while emitting a warning ("The exceptionNamespace flag is not set") on creation. When an exception matches, the PolicyReport logs the rule as skip with the exception's name in its result properties across both admission and background scans.

A Gatekeeper Constraint is applied, the violating object is still admitted, and status.totalViolations grows. Two likely settings?

Either the Constraint has spec.enforcementAction: dryrun (or warn), or the Gatekeeper webhook is running with failurePolicy: Ignore (its install default) while the webhook pod is unhealthy or timing out. In both cases, the audit loop still scans and bumps the violation count even though admission never blocks. Switch the Constraint to deny and inspect the webhook's failurePolicy and timeoutSeconds.

You write a ValidatingAdmissionPolicy with a misspelt field path. Is it rejected? Where do you find out, and what decides the runtime effect?

No, Kubernetes accepts it. CEL type errors show up afterward in status.typeChecking rather than as an apply error. At runtime, evaluating the bad field path throws an error, and failurePolicy decides what happens next: Fail blocks every matching write (per the binding's validationActions), while Ignore lets them slip through. Inspect status.typeChecking, then fix the path.

Docs to know your way around

study time, not exam time
  • kyverno.io: ValidatingPolicy / MutatingPolicy references and the community policy library.
  • open-policy-agent.github.io/gatekeeper: the ConstraintTemplate walkthrough, plus the gatekeeper-library repo for ready-to-adapt Rego.
  • kubernetes.io: Validating Admission Policy, and Dynamic Admission Control for webhook plumbing (failurePolicy, selectors, reinvocation).
  • Offline: kubectl explain validatingpolicy.spec, kubectl explain validatingadmissionpolicy.spec.validations, and kubectl get validatingwebhookconfigurations -o yaml.
  • kyverno.io/docs/policy-types/overview: the version table and deprecation timeline; /policy-types/validating-policy for evaluation, webhookConfiguration, and autogen; /guides/exceptions for the two flags.
  • open-policy-agent.github.io/gatekeeper/website/docs/howto (match fields), /mutation, /enforcement-points, and /failing-closed: the exact pages Gatekeeper tasks draw from.
  • kubernetes.io/docs/reference/access-authn-authz/validating-admission-policy and /mutating-admission-policy: field lists, parameterNotFoundAction, and CEL variables; /extensible-admission-controllers for webhook failurePolicy, timeoutSeconds, sideEffects, and matchConditions.