Kubernetes policy as code with Kyverno

Kyverno lets you write validate, mutate and generate rules for Kubernetes in YAML, roll them out in audit mode first and keep them in Git with tests. This page explains how to plan and run it in a cluster you control.

On this page

Why Kubernetes policy as code with Kyverno starts with audit, not enforce

Kyverno is a policy engine that runs as an admission controller in the cluster and also reports on resources that already exist, so teams should adopt it audit first. In audit mode, a policy evaluates requests and records violations without blocking them, which lets the platform team see how many existing workloads drift from standards before any deployment fails. Start with audit, then move each policy to enforce once its results are understood. A self-managed cluster usually has workloads that were created before any rule existed, such as privileged pods, images pulled from unapproved registries, or missing resource limits. Enforcing a rule on day one tends to block redeploys of those workloads at the worst possible time, so the first step is to measure the gap.

Pod Security Admission covers a narrow part of this problem. It enforces the three Pod Security Standards (Privileged, Baseline and Restricted) per namespace, and that is a useful floor for every cluster. Kyverno becomes relevant when the organization needs rules the standards do not express, such as requiring approved image registries, mandatory labels or owner annotations, specific securityContext values for certain namespaces, or restrictions on what platform teams may generate. Before choosing, confirm in Kyverno's own documentation which validation, mutation and generation capabilities your target version supports, and confirm which Kubernetes version your cluster runs so the admission setup matches it.

Policy reports are where audit results become work. Kyverno records outcomes for existing resources as PolicyReport objects, and the platform team should review them on a fixed schedule, assign each finding an owner and decide whether it is a fix, a documented exception or a false positive. Ask your team to answer three questions before any policy is set to enforce: which namespaces contain the most violations, which owners can fix them within the change window, and which platform workloads need an exception. Those answers determine the enforcement order and keep the first enforced policies narrow enough to defend in an audit.

Which Kyverno rule type and enforcement mode fits each goal

This table pairs each Kyverno rule type and enforcement action with the goal it fits and the risk it carries for workloads already running. Read it as a sequence: start with audit for anything that could reject existing pods, and move to enforce only after policy reports show the affected resources are fixed or excepted.

GoalRule type and actionRisk for existing workloads
Block privileged containers in application namespacesValidate rule with Enforce actionRunning pods are not evicted, but any pod update, restart or redeploy that sets privileged mode will be rejected. Check policy reports first.
Trial a new restriction before blocking anythingValidate rule with Audit actionNo requests are rejected. Violations appear in policy reports, so teams can see the backlog before enforcement starts.
Add default labels such as owner or cost centerMutate ruleMutation changes objects on admission, so existing manifests in Git may drift from the live state. Keep labels in source control to avoid conflicts with GitOps tools.
Set safe defaults such as resource limits or drop-all capabilitiesMutate rule with patch on pod specInjected values can break workloads that depend on specific settings. Test against platform and vendor charts before rollout.
Create a default network policy in each new namespaceGenerate ruleGenerated resources apply to new namespaces only unless synchronize is used. Enabling sync can overwrite manual changes, and a default deny policy can cut traffic to existing apps.
Require signed images at admissionValidate rule with verifyImages and Enforce actionUnsigned images already in use may fail on the next rollout. Confirm signing coverage in audit mode and plan exceptions for platform images.
Restrict host namespaces, host paths and hostPortValidate rule with Audit, then EnforceNode agents such as monitoring or storage drivers often need these settings. Exclude them by namespace or label before enforcing.
Enforce a rule across a sector-specific compliance baselineValidate rule with Audit first, then Enforce per namespaceScope enforcement to namespaces that have been reviewed. Enforcing cluster-wide at once can block platform components and stall releases.

How to roll out Kyverno policies from audit to enforce

This sequence moves Kyverno policies from observation to enforcement in controlled stages, so each rule is proven safe on real cluster traffic before it can block a deployment. The result is a documented set of enforced policies, a known list of exceptions and a Git repository that can recreate the whole setup.

  1. Install Kyverno into a platform namespace

    The platform team installs Kyverno into its own namespace, separate from application workloads, and sets the admission webhook to run with replicas and resource requests sized for the cluster. Confirm the chart or manifest version you install against the Kyverno documentation and your own change process, and record the version in Git. Done means the Kyverno controllers report ready, the admission webhooks are registered, and a test policy shows up in the cluster as an active resource.

  2. Start policies in audit mode

    Load the baseline policies in audit mode, with validationFailureAction set to Audit, so violations are recorded but nothing is rejected. Begin with rules that map to your own standards, such as disallowing privileged containers, requiring resource limits and blocking the latest image tag. Done means each policy is present, its status is ready, and a deliberately non-compliant test Pod is admitted but produces a policy report entry.

  3. Review policy reports across namespaces

    Read the PolicyReport and ClusterPolicyReport resources to see which workloads fail each rule, grouped by namespace and policy. Sort findings by owner and by how risky the rule is, and confirm with each team whether the failure is a real gap or a rule that needs adjusting. Done means every failing resource has a named owner and a status of fix, exception or rule change.

  4. Fix or document existing violations

    Application teams correct manifests that fail, and the platform team records anything that cannot be changed yet in a tracked list with a reason and an owner. Rules that turn out to be too broad are rewritten in Git and rerun in audit mode before anything else changes. Done means the report for each enforced candidate policy shows no unexplained failures.

  5. Add exceptions for platform workloads

    Platform components such as CNI agents, storage drivers and monitoring collectors often need privileges that application workloads do not, so the team defines PolicyException resources scoped to named namespaces and workloads. Keep each exception narrow, record the justification in the file header and set a review date in your change tracker. Done means the platform workloads appear as exempt in the reports, and no application namespace is covered by a broad exception.

  6. Switch selected policies to enforce

    Change validationFailureAction from Audit to Enforce one policy at a time, starting with the rules that had the fewest unresolved findings. Announce the change to teams, apply it through Git and watch admission results for rejected requests during a supervised window. Done means a test deployment that breaks the rule is rejected with a clear message, and existing compliant workloads keep running.

  7. Keep policies in Git with tests

    Store every policy, exception and test fixture in a Git repository, and run the Kyverno CLI against sample manifests in continuous integration so that a rule change must pass its expected pass and fail cases before merge. Connect the repository to your GitOps tool so the cluster state matches the reviewed branch. Done means a deliberately broken policy change fails the pipeline, and the cluster's live policies match the main branch.

  8. Re-check reports after each change

    After each enforcement change and each Kyverno upgrade, review the policy reports again and confirm that exceptions still match live workloads. Retire exceptions that no longer apply and record the date and result. Done means the reports show only expected results, and the review record is kept with the Git history.

How a request moves through Kyverno admission and reporting

The flow starts when a user or a GitOps tool such as Argo CD submits a change to the kube-apiserver. The API server calls Kyverno's admission webhooks, where mutate rules run first and validate rules run after them. In Enforce mode a failing validate rule denies the request, while in Audit mode the request is allowed and the violation is recorded. Background scans then write results to policy reports, so check both the admission path and the report output before moving a policy to enforce.

Admission path for a change, with audit and enforce outcomes diverging at validation.

Handling exceptions for platform and system workloads

CNI plugins and CSI node plugins run as DaemonSets on every node, and they usually need host networking, host paths, or privileged containers to program routes, attach volumes, and manage devices. Blocking these outright breaks the cluster, so the exception has to target the workload precisely. Write the exception against the DaemonSet's namespace and a stable label set, and list only the specific rule it overrides, such as the host namespace rule or the privileged container rule, rather than the whole policy. Keep the namespace for these components dedicated to them so that application teams cannot deploy look-alike pods into it.

  • Name the exact rule: Exempt the privileged rule for the CNI namespace, not every Pod Security rule.
  • Pin the image source: Match on the approved registry path so a copied image from elsewhere does not inherit the exception.
  • Restrict who can create pods there: Use RBAC so only the platform team can create workloads in that namespace.
  • Record the justification: Note which capability the component needs, such as host network or device access, and why.
  • Review on upgrade: New chart versions can add privileges, so re-check the exception after each version change.

Before you finalize the exception, confirm the exact securityContext fields the chosen chart version requires and test that nothing else in the cluster matches the selector.

Security and operational risks of policy engines in admission

A policy engine in admission sits on the path of every create and update request, so its failures and its configuration become cluster-wide risks. The six risks below connect availability, recovery, change control and supply chain, and each one needs a decision before enforcement begins.

Webhook availability and failure policy

Kyverno runs as an admission webhook, so the API server calls it before objects are stored. The webhook's failure policy decides whether requests are rejected or allowed when the engine cannot answer. A fail-closed setting protects policy coverage but can stop deployments and node-level changes during an outage. Check the failure policy for each rule set, the number of Kyverno replicas, and whether the webhook timeout fits your API server latency. Test what happens when the Kyverno pods are down.

Kubernetes authentication docs

Policies that block cluster recovery

An enforce-mode rule that applies to system namespaces, control plane add-ons or recovery tooling can prevent you from restoring the cluster. For example, a rule requiring a label on every pod may block the pods that would restore a failed component. Exclude kube-system and your platform namespaces by design, not by memory, and keep a documented break-glass path that does not depend on the engine. Rehearse a restore with the policies active to confirm that recovery workloads still schedule.

Mutation surprises

Mutate rules change objects after the user submits them, so the stored object may differ from the manifest in Git. Injected labels, default resource limits or security context fields can alter scheduling, break selectors or change application behavior. Mutations also run in a defined order with other webhooks and in-place changes can confuse GitOps drift detection. Record every mutation in a policy inventory, show the diff in test output, and confirm which application teams expect each change.

Who can change policies

A ClusterPolicy is a cluster-scoped object, and anyone who can edit it or the Kyverno configuration can weaken controls for the whole cluster. Limit write access to policy resources and to the Kyverno namespace through RBAC, separate policy authors from cluster administrators, and log changes through the Kubernetes audit log. Review who holds permissions to exceptions, since an exception can silently exempt a workload. Confirm this model with your identity team before the first rule is enforced.

Supply chain of the Kyverno chart and images

Kyverno runs with broad read access and sits in the admission path, so a compromised chart or image would have high impact. Pin chart and image versions, mirror both into your private registry, and verify provenance according to the project's published release artifacts. Track Kyverno releases and your Kubernetes version support together, since the engine must work with the cluster version you run. Ask who approves a new chart version and how you roll it back.

Policy drift between clusters

When each cluster receives policies by hand, rules diverge over time, and a workload that passes in staging may fail in production or the reverse. Store policies, exceptions and test cases in one Git repository, deliver them with a GitOps tool to every cluster, and report the deployed revision per cluster. Differences that are intentional, such as a stricter rule for a regulated cluster, should appear as named overlays rather than edits made in place.

Keeping Kyverno policies in Git with tests before they reach clusters

Treat every Kyverno policy, exception and test case as code that lives in Git and reaches clusters only through a reviewed change. The repository should hold the ClusterPolicy and Policy manifests, the PolicyException resources that carve out platform workloads, and a folder of sample resources that the policies are expected to accept or reject. Pull requests are the control point: a reviewer should be able to see, in one diff, what a rule blocks, which namespaces or workloads are exempt and why, and whether the matching test changed alongside it. Ask your team to agree in advance who may approve exceptions, since an exception is effectively a permanent hole in a control unless it has an owner and an expiry review.

Run the Kyverno CLI in CI against those sample resources so each pull request shows whether policies still produce the expected pass, fail or skip results. Test cases should cover both sides of every rule: a compliant workload that must pass, a non-compliant one that must fail, and the platform workloads that must match an exception and nothing broader. Mutation and generate rules need their own cases, because the expected output is a changed or new resource rather than a verdict. Coverage is the team's design decision, not something the tool supplies. Decide which policy categories and which resource kinds are mandatory for a merge, and record that standard in the repository so reviewers can enforce it. Confirm the Kyverno CLI version your CI image installs matches the Kyverno version running in the cluster, since rule behavior can differ between releases.

Deploy from Git through your GitOps controller rather than applying policies by hand, so the cluster state always matches the reviewed commit. Keep policy sets in their own application with a sync order that installs Kyverno before the policies that depend on its CRDs, and keep platform exceptions in the same repository so an exemption cannot reach a cluster without passing review. Plan for the operational edge cases: a policy that is promoted from audit to enforce should move through its own pull request with the audit results attached, and a rollback should be a Git revert, not an emergency edit in the cluster. Ask any implementation partner to show the CI job, the test layout and the sync configuration as part of the handover, because those artifacts are what your team will maintain after the engagement ends.

What to confirm before you commit to Kyverno in your environment

Kyverno runs inside your cluster and touches every admission request, so its release, your Kubernetes version, your distribution and your image supply chain all have to line up. The cards below list what to confirm with the Kyverno project, your distribution vendor and your own platform team before you write the first enforcing policy.

Kyverno release and Kubernetes version support

Each Kyverno release targets a specific range of Kubernetes minor versions, and that range moves as Kubernetes releases and ends support. Check the compatibility matrix for the Kyverno release you plan to install against the Kubernetes version you run today and the version you plan to upgrade to. Kubernetes support windows are published on the releases page, so a cluster you upgrade later may need a newer Kyverno first. Ask whether the chosen release has a supported upgrade path from your current one.

Kubernetes releases

Distribution and managed service interaction

Confirm with your distribution vendor or managed service provider whether they allow Kyverno, whether they ship their own admission webhooks that could conflict with it, and whether any built-in policies overlap your rules. Ask who supports the Kyverno install when the distribution, the managed control plane and Kyverno all touch admission. Some managed services restrict webhook configuration or API server flags, which can limit what Kyverno can see or enforce. Get those answers in writing before you design policies that depend on them.

Image signature verification requirements

If you plan to verify image signatures at admission, decide which signing method your build pipeline uses, where signing keys or certificates live, and which transparency log, if any, must be checked. Ask your signing and CI teams whether signatures are produced for every image that reaches production, including base images and sidecars. Confirm how Kyverno will reach your signing infrastructure and what happens when that path is unavailable during an outage. Image signing gets its own treatment in the sibling topic on cosign, so use this card to settle requirements, not implementation.

Air-gapped image mirroring

Kyverno's controller and background-scan images, and any helper images it pulls, must be available from a registry your nodes can reach. In a disconnected network, ask the Kyverno project for the full list of images each release uses, then confirm your mirror holds them at the tags you intend to deploy. Check whether Helm chart values can point every image at your internal registry, and whether the chart or its dependencies pull anything from the public internet at install time. Plan how signed images and policy bundles will move across the boundary.

Performance under your object count

Kyverno evaluates policies against admission requests and, through background scans, against existing resources. Its cost grows with the number of policies, the number of matched resources and the size of each object. Ask for documented sizing guidance for your cluster count, object count and request rate, and for the resource requests the Kyverno controllers need at that scale. Run a load test against a representative copy of your largest cluster, and measure admission latency with policies in enforce mode before you roll out to production.

Support model and upgrade ownership

Confirm who owns Kyverno upgrades, who answers when a policy blocks a production deployment, and how fast fixes arrive for issues you find. If your platform team runs Kyverno, check the support terms that apply to your installation. If a partner runs it for you, ask for the written scope covering policy authoring, exceptions, testing and the upgrade cadence. Ask how your policy repository will be tested on each Kyverno upgrade, so an upgrade does not change enforcement on the same day it lands.

Questions teams ask before hiring help with Kyverno

What drives the cost and effort of a Kyverno rollout?

The biggest driver is how many policies you need and how many clusters they must cover. Effort rises with the number of rules that need custom logic, the number of workload teams who must change their manifests before enforcement, and the amount of existing cluster state that must be reviewed first. The engagement is usually priced as a fixed scope agreed in writing, so the quote follows from the list of policies, clusters, environments and deliverables. Ask for the cost split between discovery, policy authoring, testing, rollout support and handover, and confirm which items are one-time and which recur. Ongoing policy changes, new Kubernetes versions and Kyverno upgrades are the recurring parts.

How long does a phased Kyverno rollout take?

Duration depends on cluster count, policy scope and how many teams must adapt. A phased rollout normally starts with inventory and audit mode in one non-production cluster, then moves policies to enforcement one group at a time, with exception handling for platform workloads in between. Each phase waits for policy reports to show the violations are understood and fixed. Ask any partner to state the phases, the exit criteria for each, and which parts depend on your change windows and application teams. Treat any duration given without a written scope as a placeholder until the scope is agreed.

What does the work need from our platform and security teams?

Plan for named people in platform engineering, security and at least one owner per workload area. Platform engineers provide cluster access, the GitOps repository and pipeline access, and a non-production cluster that matches production admission settings. Security owners approve the policy catalog, decide which controls are blocking and which are audit only, and review exception requests. Application owners confirm how their workloads should comply, for example which images or security contexts they use. Confirm early who approves exceptions and how long an exception may last, because unresolved exceptions are the most common reason enforcement stalls.

Can an internal team roll out Kyverno without outside help?

Yes, a team with solid Kubernetes administration, admission control experience and GitOps practice can roll out Kyverno alone, and many do. The work that is easiest to underestimate is policy testing, audit analysis across existing resources, and coordinating exceptions for system components such as controllers and monitoring agents, which can break if blocked. Decide honestly whether your team has time for audit cycles and handover documentation. A partner can fill gaps in policy design, test harnesses in CI, and evidence for compliance reviews, while your team keeps ownership of the policies and the cluster.

How does Kyverno differ from OPA Gatekeeper and built-in CEL policies?

At a high level, Kyverno expresses policies as Kubernetes YAML resources and can validate, mutate and generate resources, which many teams find closer to the way they already write manifests. OPA Gatekeeper uses the Rego language with constraint templates and constraints, which suits teams already invested in Rego and in the Open Policy Agent ecosystem. Built-in CEL policies use Common Expression Language within the Kubernetes API, with fewer moving parts but a narrower feature set. The choice depends on your team's skills, the policies you need to generate or mutate, and how you test policy in Git. A sibling topic covers this comparison in more depth.

What does ongoing Kyverno maintenance look like?

Maintenance is recurring work: reviewing policy reports, updating policies when workloads or Kubernetes versions change, upgrading Kyverno itself, and handling new exception requests. Each Kubernetes minor release can change resource behavior, so policies should be re-tested against the cluster versions you run. Kubernetes minor releases happen about three times a year, and the project maintains only the three most recent minor versions, so plan upgrades of the policy engine alongside cluster upgrades. Ask for a written list of recurring tasks, who performs them, and whether a retainer covers policy tests, upgrades and continuous review.

Does DeployOpen issue a compliance certificate for our Kyverno policies?

No. DeployOpen prepares systems, controls and evidence for compliance assessments, including policy definitions, audit reports and exception records, but independent auditors and certification bodies issue any audit report or certification. Ask what evidence will be delivered, in what format, and how it maps to the control framework your assessor uses. Confirm with your assessor which artifacts they accept before the policies are written, since that avoids rework during the assessment.

How DeployOpen scopes and delivers Kyverno policy work

DeployOpen plans, implements and hands over Kyverno policy work inside clusters and infrastructure you control, with the policy set, test suite and rollout sequence agreed in writing before build starts. Engagements are fixed-scope, so the policies covered, the clusters involved and the deliverables are defined up front.

How we scope

  • Inventory the clusters, namespaces and workloads that Kyverno policies will govern, and name the owners for each
  • Agree which validate, mutate and generate policies are in scope, and which are deferred to a later phase
  • Define the audit-first rollout, exception process for platform workloads and the evidence your reviewers expect

How we build

  • Write policies in YAML, store them in Git and run them against test manifests in CI before any cluster change
  • Deploy policies in Audit mode first, review policy reports with your team and fix false positives before enforcing
  • Document exceptions for platform workloads with named approvers and expiry dates, and verify each one in a test cluster

How we hand over

  • Deliver the policy repository, test suite, rollout runbook and a list of exceptions with their justifications
  • Walk your platform and security teams through reading policy reports and changing policies through pull requests
  • Confirm the handover is complete in writing, so your team can add, tune and retire policies without DeployOpen

How we support

  • Offer ongoing support, Kyverno version upgrades and policy updates as a retainer, scoped in writing
  • Review new policy requests and Kubernetes version changes against the existing policy set and exception list
  • Retest policies after cluster upgrades so enforcement stays aligned with what your team has agreed

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.