DevopsIntermediate

Policy as Code: Guardrails That Survive On-Call

DeveloperHat Team
22 min read

TL;DR

OPA, Kyverno, or native admission policy — which engine fits which rule, how to roll a guardrail out without paging anyone, and the failure modes that decide whether policy as code helps or hurts.

Every platform team reaches the same moment: the third time a privileged pod, an untagged namespace, or an unsigned image reaches production, somebody asks why the cluster did not simply refuse it. The answer is usually that the rule existed — in a runbook, in a wiki page, in a Slack thread from March — but nowhere the API server could read it. Policy as code moves the rule into the request path: a workload that violates it never becomes an object in etcd, and the rejection is logged where the team can find it.

The short version: keep policies in Git and review them like code, test every policy in CI before it ships, start each new policy in audit or warn mode and watch what it would have blocked, enforce only when the false-positive rate is boring, and treat the policy engine itself as a critical system — because a webhook that fails closed can stop every deploy in the cluster, and one that fails open is a guardrail made of paper. The engine choice matters less than the operating model around it: for simple validation, Kubernetes' native admission policy is now good enough; for mutation, generation, and reporting, Kyverno is the pragmatic pick; for rules that must also run outside Kubernetes, OPA with Gatekeeper is the only one of the three that travels. Versions as of this writing: OPA 1.23.0 (26 November 2026), Kyverno 1.20 (11 November 2026), and native ValidatingAdmissionPolicy, generally available since Kubernetes 1.30.

The policy pipeline: a rule is code before it is a gate Every rule is reviewed, tested, shipped, and observed — the webhook is only the last step. Policy repo Git · review CI tests opa test · chainsaw Webhook admission check Engine OPA · Kyverno · VAP etcd persisted Deny + PolicyReport a rejection is logged, not silent The request that passes is persisted; the request that fails leaves a report the team can find.

Why admission is the gate that matters

Kubernetes gives a write request four chances to be stopped before it becomes a persisted object: authentication, authorization, mutating admission, and validating admission. The first two answer who you are and whether you may act. Admission answers a different question: whether the object itself is acceptable, regardless of who submitted it. That distinction is the whole point of policy as code. RBAC can stop an intern from deleting a namespace; it cannot stop a senior engineer from deploying a pod with privileged: true, because that engineer is allowed to deploy pods. Only a rule that inspects the object can catch that, and only admission runs on every write, from every client, with no way around it short of cluster-admin access to the API server configuration itself.

Two properties of the admission gate shape everything that follows. First, it sees the final object: mutating admission runs before validation, so a policy that checks resource limits sees the limits after any defaulting webhook has added them. Second, it is a choke point, which is both its power and its risk. A policy engine that is down, slow, or misconfigured does not degrade gracefully by default — it either blocks deploys across the cluster or, if someone set it to fail open, silently stops enforcing. Every decision in this guide — which engine, which failure mode, which rollout — is a decision about that choke point.

There is also a limit worth stating plainly. Admission only sees writes. It cannot fix the privileged pod that is already running, the image that was pulled last month, or the secret that leaked in a log. That is why the engines that do background scanning matter: Kyverno re-evaluates existing resources and writes the results to PolicyReport objects, and Gatekeeper's audit runs the same constraints against what is already in the cluster. A guardrail that only judges new arrivals leaves the existing estate unjudged, and the existing estate is where the risk already lives.

The three engines, head to head

The field has consolidated around three answers, and they are less interchangeable than their marketing suggests. Each one is the right default for a different shape of team.

OPA + GatekeeperKyvernoNative admission policy
LanguageRego (OPA 1.x uses Rego v1 by default)CEL, plus JMESPath in legacy policiesCEL
Runs asWebhook + audit controllerWebhook + controllersIn-process, in the API server
MutationNo (validation only)Yes — defaults, labels, generated resourcesYes — MutatingAdmissionPolicy, stable in 1.36
GenerationNoYes — NetworkPolicy per namespace, and moreNo
ReportingConstraint violations via auditPolicyReport per resource, built inAudit action only, no per-resource report
Outside KubernetesYes — Terraform, CI, APIs, anythingNo — Kubernetes onlyNo — Kubernetes only
Failure modeWebhook: can take the cluster downWebhook: can take the cluster downIn-process: cannot take the cluster down

OPA with Gatekeeper is the generalist. OPA itself is a policy engine that evaluates Rego against any JSON input, and Gatekeeper is the Kubernetes integration that turns Rego constraints into admission webhooks plus an audit loop. Its strength is portability: the same Rego that denies a privileged pod can deny a Terraform plan that opens port 22 to the world, because OPA does not care where the input came from. Its cost is a second language. Rego is expressive — it is a Datalog-style language, and policies that join data across resources read like small programs — but it is a language the team has to learn, and a language only one or two people on the team actually know is a bus-factor problem. OPA is a graduated CNCF project, and the current release, 1.23.0, carries a breaking change worth knowing before you upgrade: bundles are now rooted at their .manifest file, so bundles loaded from disk with the manifest nested below the path you passed will be rejected. Rebuild them with opa build rather than discovering this in the deploy pipeline.

Kyverno is the Kubernetes-native. Policies are Kubernetes resources written in YAML, the rules are CEL expressions or JMESPath, and the engine does things the other two cannot: mutate a request (add the label, set the default), generate a resource when another one appears (a NetworkPolicy for every new namespace), verify image signatures, and write a PolicyReport for every resource it evaluated. That breadth is why platform teams pick it: one engine covers the guardrail, the defaulting, and the audit trail. Its cost is scope and churn. Kyverno's CEL policy types reached general availability in 1.17, announced in February 2026, and the legacy ClusterPolicy and Policy types were deprecated at the same time. Kyverno 1.20, released 11 November 2026, now blocks creating or updating resources through those legacy APIs — new policies must use the CEL types under policies.kyverno.io/v1. Any guide, tutorial, or copied YAML still showing ClusterPolicy is describing the old engine. The churn is real, but the direction is clear: CEL, aligned with the API server's own validation language, is the future of the project.

Native ValidatingAdmissionPolicy and MutatingAdmissionPolicy are the boring option, and boring is a compliment here. The policies are CEL expressions evaluated inside the API server — no webhook, no extra pods, no network call, nothing that can fail and take deploys down with it. ValidatingAdmissionPolicy went generally available in Kubernetes 1.30, and MutatingAdmissionPolicy followed to stability in 1.36. The cost is capability: no mutation of the interesting kind, no generation, no background reports beyond the audit action, and no way to consult data outside the API server. A rule that needs to check an external system — is this image signed, is this ticket approved — cannot live here. But a surprising number of real guardrails do not need any of that. "Every container sets CPU and memory requests and limits" is a CEL expression, and it does not need a webhook to evaluate it.

The honest summary: if the rule is simple validation and CEL can express it, use the native policy — it is the only option that cannot break the cluster. If the rule needs mutation, generation, or a per-resource report, use Kyverno. If the same rule must also run in Terraform plans, CI pipelines, or service authorization, use OPA. Most teams end up with two of the three, not one: native policy for the simple rules, and one engine for the rest. That is fine. Two engines with clear boundaries beat one engine stretched past what it does well.

Five layers, one rule — and every layer can fail on its own Policy source — a Git repo, reviewed like application code Test & review — opa test, conftest, Chainsaw run in CI on every change Distribution — signed bundles and OCI images, one version per cluster Enforcement — the admission webhook, fail-closed, with a timeout budget Observation — PolicyReport, audit log, and alerts on the webhook itself A policy that cannot be tested in CI will be tested in production — at 3 a.m.

Writing policies that survive contact with reality

A policy is code, and it fails the way code fails: on the input nobody tested. The two most common failures are a rule that is broader than intended — it matches the CronJob's pod template as well as the Pod, or it fires on the system namespaces — and a rule that is narrower than intended, usually because the author tested it against one example and shipped it. Both are fixed the same way: a test for the allow case, a test for the deny case, and a test for the case the author is most worried about.

The Rego version of the most-written policy in the field — no privileged containers — looks like this in OPA 1.x, where Rego v1 syntax is the default:

package kubernetes.admission

deny contains msg if {
	input.request.kind.kind == "Pod"
	container := input.request.object.spec.containers[_]
	container.securityContext.privileged
	msg := sprintf("container %v runs privileged", [container.name])
}

Three details matter. The rule iterates containers[_], so it catches the second container in a pod, not just the first. It checks input.request.kind.kind, so it does not fire on Deployments or CronJobs whose pod templates happen to contain the same field — the admission request for a Deployment carries a Deployment object, and a policy that reads spec.template.spec.containers on a Pod-shaped path silently matches nothing. And the denial message names the container, because a message that says "policy violated" at 3 a.m. is a page that takes ten minutes longer to resolve than one that says which container and why.

The same rule in Kyverno's CEL policy types, current as of 1.20:

apiVersion: policies.kyverno.io/v1
kind: ValidatingPolicy
metadata:
  name: require-requests-limits
spec:
  validationActions: [Deny]
  matchConstraints:
    resourceRules:
      - apiGroups: [""]
        apiVersions: ["v1"]
        resources: ["pods"]
        operations: ["CREATE", "UPDATE"]
  validations:
    - expression: "object.spec.containers.all(c, has(c.resources.requests) && has(c.resources.limits))"
      message: "Every container must set CPU and memory requests and limits."

The structure is the lesson: matchConstraints narrows the blast radius to pods on create and update, and the CEL expression is one readable line. A platform engineer who has never written Rego can read this policy, which is not a small thing — the person who debugs a policy at 3 a.m. is rarely the person who wrote it. CEL's expressiveness is narrower than Rego's, and that is a feature for guardrails: a rule the on-call engineer can read is a rule the on-call engineer can trust.

Testing is where the two ecosystems differ in tooling but agree in principle. OPA ships opa test, which runs test cases written in Rego against the policy, and conftest applies the same idea to any structured input. Kyverno's ecosystem has Chainsaw, an end-to-end test runner that applies a policy to a real cluster and asserts on the outcome. Whichever you use, the test suite belongs in the same repository as the policy, runs in CI on every change, and includes the negative test — the workload the policy must allow. A suite that only tests denials will happily ship a policy that denies everything, and the team will discover that in production, all at once.

Two anti-patterns deserve naming. The first is the policy with no matchConstraints or equivalent scoping: it evaluates against every resource in the cluster, including the ones the platform team itself creates, and the first time it fires on a system workload the team learns about it from the platform's own pager. Scope every policy to the resources it is about, and exclude the namespaces the platform owns. The second is the policy that duplicates a built-in control. Pod Security Standards, enforced by the built-in PodSecurity admission plugin, already cover privileged containers, host namespaces, and the rest of the standard profiles. Writing a Rego policy that re-implements the restricted profile is work that buys nothing — configure the built-in plugin for the baseline, and spend the custom-policy budget on the rules that are specific to your estate.

Enforce, warn, or audit — the failure mode is the product

Every engine offers three postures, and the choice between them is the decision that determines whether policy as code is experienced as a guardrail or as an outage. Native admission policy names them validationActions: Deny, Warn, and Audit. Kyverno's CEL policies use the same words. Gatekeeper's equivalent is the constraint's enforcementAction: deny, dryrun, or warn.

Audit first, always. A new policy starts in audit mode, and stays there until the team has read what it would have blocked. The audit log — or Kyverno's PolicyReport, which is easier to query — answers the only question that matters at this stage: is the policy catching real violations, or is it catching the platform's own workloads, the legacy service nobody owns, and the third-party operator that cannot be changed? A policy that would have blocked fifty legitimate deploys in its first week is not a policy; it is a misconfigured rule with a blast radius. The audit phase is where that gets discovered, for free.

Warn second, for the policies that are about behaviour, not safety. A warning is visible to the person applying the change — it appears in the kubectl output — without stopping the deploy. It is the right posture for rules the team wants to migrate toward: "this image is not from the approved registry" during the quarter the team is migrating registries, or "this workload has no owner label" while labels are being backfilled. Warnings have a failure mode of their own: people stop reading them. A warn-mode policy with no one watching the warning count is a policy that has already been forgotten, so warn mode needs an owner and a date, not just a setting.

Enforce last, and only for the policies where a violation is a genuine incident. No privileged containers, no images from outside the approved registries, no hostNetwork on multi-tenant clusters — these are enforceable because the correct response to a violation is "do not deploy this," and because the team can name the person who fixes it. The test for whether a policy is ready to enforce is simple: run it in audit for two weeks, read every hit, and enforce it only when every hit was a real violation and every real violation had an owner who could fix it. If the audit log is full of hits nobody owns, the policy is not ready — the team has an inventory problem, not an enforcement problem.

The failure mode of the webhook itself deserves the same discipline. Both Kyverno and Gatekeeper register admission webhooks, and both default to failing closed: if the webhook does not answer, the API server rejects the request. Failing closed is correct for a security control and catastrophic for availability if the webhook is slow or down, because it turns a policy-engine outage into a deploy outage across every namespace the webhook covers. Three mitigations, in order of importance: keep the webhook's timeout tight (the API server's default webhook timeout is 10 seconds, which is an eternity for an admission check — set it lower and measure), exclude the namespaces the platform itself needs to recover with (kube-system and the webhook's own namespace, at minimum), and monitor the webhook's latency and error rate as a production service, because that is what it is. The native policy option avoids all of this by running in-process, which is the strongest argument for using it wherever it can express the rule.

There is one more failure mode, and it is the one teams forget: the policy engine is itself a privileged, security-critical component. It reads every admission request, which means it sees every secret reference, every image, every workload definition in the cluster. Kyverno's 1.19.2 patch release fixed 24 published security advisories, several of them privilege-escalation paths through the engine itself. That is not a reason to avoid the tool — every serious project has patch releases like that — but it is a reason to patch the engine on the same schedule as the API server, and to treat a policy engine that has not been updated in a year as a risk, not as stability.

The rollout that does not page anyone

The rollout is a sequence, and the order is the whole technique. First, the baseline: enable Pod Security Standards at the restricted level in audit mode, and let the platform team see how far the estate is from it. Most estates are further than their owners believe, and the audit log is the evidence that makes the remediation budget real. Second, the inventory: list the workloads that violate the baseline, give each one an owner, and fix the ones that are trivially fixable — the privileged flag that was copied from a tutorial, the missing resource limits, the image tag that is latest. Third, the first custom policy, in audit mode, for the rule the team cares most about. Fourth, warn mode for one release cycle, with the warning count on a dashboard somebody actually looks at. Fifth, enforce — one policy at a time, never a batch, so that when something goes wrong the team knows which policy did it.

Exceptions are part of the design, not a failure of it. Every estate has a workload that legitimately needs what the policy forbids: the monitoring agent that needs host networking, the legacy service that cannot set resource limits without a rewrite. The exception mechanism must be explicit, time-boxed, and visible. Kyverno's PolicyException resource and Gatekeeper's exemption mechanisms both exist for this; a hand-edited namespace label that nobody reviews is not an exception mechanism, it is a hole. Every exception carries an expiry date and an owner, and the expiry is enforced by a report that lists the exceptions expiring this month — because an exception without an expiry is a policy that was quietly deleted for one workload.

The operating rhythm after rollout is small and regular: a weekly review of the PolicyReport or audit log, a monthly review of exceptions and their expiries, and a policy change that goes through the same review as application code, because it is code, and it runs in the request path of every deploy. Our GitOps guide covers the mechanics — policies in a repository, reviewed in pull requests, applied by the same pipeline that applies the rest of the platform — and the discipline is the same. A policy change that bypasses review is a change to the cluster's security posture made by one person with no second pair of eyes, and the incident review will say so.

Recommendation

For a platform team starting from nothing, the order of work is: enable Pod Security Standards at the restricted level in audit mode and fix what it finds; write the three or four guardrails that matter most — no privileged containers, approved registries only, resource requests and limits required, no latest tags — as native ValidatingAdmissionPolicies where CEL can express them; add Kyverno when a rule needs mutation, generation, or a PolicyReport the team can query; and add OPA only when the same rule must run outside Kubernetes, in Terraform plans or CI. Keep every policy in Git, tested in CI, rolled out audit-first, and enforced one at a time. Patch the engine like the critical system it is, exclude the platform's own namespaces from the webhook, and give every exception an owner and an expiry date.

Pick the engine by what the rule needs, not by the logo Start at the top. Stop at the first yes — and start in warn mode either way. What does the rule need? validate · mutate · share Simple validation native ValidatingPolicy Mutate / generate / report Kyverno CEL policies Same rules off-cluster OPA / Gatekeeper If the rule needs data the API server does not have, a webhook is the only honest answer.

Architecture Decision

Decision: Run policy as code with native Kubernetes ValidatingAdmissionPolicy for simple CEL-expressible validation, Kyverno 1.20 CEL policies for mutation, generation, image verification, and PolicyReport-based auditing, and OPA 1.23 with Gatekeeper only where the same rule must also run outside Kubernetes. All policies live in Git, are tested in CI, and roll out audit → warn → enforce, one policy at a time.

Context: The platform team runs multi-tenant clusters where any engineer can deploy, and the same three violations — privileged pods, unapproved registries, missing resource limits — keep reaching production. RBAC cannot express object-level rules, and the rules currently live in runbooks nobody reads. The team is small, the on-call rotation includes people who did not write the platform, and a policy engine outage must not become a deploy outage.

Options considered: (1) The layered model above. (2) Kyverno alone for everything — simplest to explain, but it puts every rule behind a webhook, including rules the API server could enforce in-process, and it leaves the team exposed to the webhook's availability. (3) OPA and Gatekeeper alone — the most portable, but it means learning Rego, running a webhook for rules CEL could express natively, and giving up Kyverno's mutation and generation. (4) Native admission policy alone — the most available option, but it cannot mutate, generate, or report per resource, and it cannot consult data outside the API server. (5) No policy engine, and instead a CI check on manifests — cheapest, and it catches what goes through the pipeline, but it catches nothing applied directly with kubectl, nothing changed by an operator, and nothing that drifts after deploy.

Why this one: The layered model puts each rule on the cheapest mechanism that can express it, which keeps the webhook's blast radius as small as possible: most rules never touch a network call. Kyverno earns its place on the rules the native policy cannot express, and its PolicyReport is the audit trail the team queries every week. OPA earns its place only where portability is a real requirement, not a hypothetical one. And the audit-first rollout is what makes the whole thing survivable: the team learns what the estate actually looks like before any deploy is blocked.

What it costs you: Two engines to operate and patch instead of one, and a third if OPA is genuinely needed. CEL's expressiveness ceiling means some rules will be awkward or impossible natively, and the team has to know where that ceiling is. Kyverno's migration from legacy to CEL policy types is a real project for teams on older versions — 1.20 blocks new legacy policies, so the migration is not optional for long. Webhooks need latency and error-rate monitoring, timeout tuning, and namespace exclusions, which is operational work that never appears in the demo. And every policy needs an owner, a test, and a review, which is a permanent tax on the platform team's time.

When to reverse it: On a single cluster with one team and a short list of trusted deployers, the whole model is overhead — Pod Security Standards plus code review is enough, and the ceremony can wait until the second team arrives. Reverse toward a single engine if the team is small enough that operating two is the bottleneck: Kyverno alone is the usual consolidation, since it covers the most ground. Reverse the OPA choice if the non-Kubernetes use case never materialises — a rule that was supposed to run in Terraform plans but never did is a second engine paying rent for nothing. And reverse the enforce posture, not the policy, when the audit log shows a rule firing on workloads the team cannot change: the rule was wrong, or the estate was not ready, and warn mode is the honest answer until one of those changes.

When NOT to use policy as code

The model is not free, and there are situations where the honest answer is simpler. Do not build a policy engine for a single-team cluster where everyone who can deploy is in the same room — Pod Security Standards and a code review will catch the same violations with a fraction of the moving parts. Do not enforce a policy you have not run in audit mode; enforcement without an audit phase is how a routine Tuesday becomes a deploy outage, and the postmortem will note that the policy had never been observed in the wild. Do not write a custom policy for a rule a built-in control already enforces — the Pod Security Standards exist precisely so teams stop re-implementing them in Rego. Do not put a webhook in the path of the namespaces the platform needs to recover with, including the webhook's own namespace; the day the engine is down is the day that exclusion earns its keep. And do not treat the audit log as a compliance artifact: if nobody has ever read the PolicyReport, run the exercise — pick a policy, reconstruct what it blocked this month, and see whether the report can actually answer the question. If it cannot, the model is not running yet, whatever the console says.

The test for whether policy as code is worth it is one question: if a workload that violates your most important rule were submitted right now, would the cluster refuse it — and would anyone know it tried? If the answer is "it would deploy, and we would find out in the next audit, if there is one," the model pays for itself the first time a privileged pod is rejected at the gate instead of discovered in an incident review. If the answer is already "it would be denied, logged, and visible in the weekly report," then the model is already running — keep it running, and spend the effort on the next risk. The goal was never to make the cluster clever. It is to make the guardrails boring: a rule is written once, reviewed like code, tested before it ships, observed while it runs, and enforced only when the team has seen what it catches. One repository, one pipeline, one report — and a webhook that fails closed, monitored like the production service it is. That is the whole discipline, and it is enough.

Our platform engineering guide treats guardrails as a product the platform team ships to its users, not as a control imposed on them — the framing matters, because a guardrail the teams experience as help gets adopted, and one they experience as a gate gets routed around. And the audit discipline here is the same one our secrets at scale guide applies to credential access: a log nobody reads is not a control, whatever it records.

Why This Matters

Understanding the business and technical context helps you make informed decisions rather than blindly following patterns.

Trade-offs to Consider

Every architectural decision involves trade-offs. Consider your specific requirements, team expertise, and scale when evaluating options.

When NOT to Use This

Knowing when a solution doesn't apply is as valuable as knowing when it does. Consider alternatives for your specific situation.

Decision Framework

Use this framework to evaluate whether this approach is right for your use case based on your specific constraints and requirements.

Share this articleShare on XShare on LinkedIn

Keep the decision frameworks coming

One practical architecture guide a week — patterns, trade-offs, and when not to use them. No spam, unsubscribe anytime.