Kubernetes Policy as Code: OPA vs. Kyverno for Enterprise in 2026
Kubernetes policy as code enforces cluster governance at admission time. Compare OPA Gatekeeper vs Kyverno and learn which tool fits your enterprise.
Kubernetes policy as code is how engineering teams enforce governance at cluster admission time — blocking non-compliant workloads before they ever reach etcd. Without it, the gap between what your security team documents and what actually runs in production widens with every deploy. Teams operating more than a handful of clusters, or those under SOC 2, PCI, or ISO 27001 audit obligations, cannot close that gap manually. The volume is too high and the blast radius of a misconfigured container is too large.
The two dominant engines for Kubernetes policy as code in 2026 are OPA Gatekeeper and Kyverno — and the choice between them shapes not just your cluster governance posture but your operational overhead for years. OPA brings a powerful general-purpose policy language (Rego) that scales across your entire stack. Kyverno keeps policies in native YAML and handles the most common Kubernetes governance patterns with almost no learning curve. Picking the wrong one means either outgrowing your policy layer in 18 months or spending weeks teaching your ops team a declarative query language.
This guide covers both engines in depth — how admission control works, when to use OPA versus Kyverno, how to extend policy enforcement into your CI/CD pipeline, and real policy examples for enterprise compliance requirements. For how policy enforcement fits inside a hardened delivery pipeline, see our post on DevSecOps and CI/CD pipeline security.
What Kubernetes Admission Control Actually Does
Every resource creation or mutation request in Kubernetes — a Pod, a Deployment, a ConfigMap — goes through the API server before it is written to etcd. The API server processes each request in a fixed sequence: authentication, authorization (RBAC), and then admission control. Admission control is the last checkpoint before persistence, and it is where policy engines live.
Kubernetes exposes two webhook admission controller types: MutatingAdmissionWebhook and ValidatingAdmissionWebhook. Mutating webhooks run first and can modify the incoming object — adding default labels, injecting sidecars, or setting resource limits that the manifest omitted. Validating webhooks run after mutation and make a binary allow/deny decision. Both OPA Gatekeeper and Kyverno implement admission webhooks: they register themselves with the API server, receive every applicable resource request as an HTTPS POST, evaluate it against your policy set, and return an admission response.
- →Mutating webhook use cases: injecting required labels, setting default resource limits, adding security context defaults, enabling pod security admission labels on newly created namespaces.
- →Validating webhook use cases: blocking containers that request host networking, enforcing that all images come from an approved registry, requiring resource limits on every container, preventing privileged escalation.
- →CEL validation (Kubernetes-native, no webhook): Kubernetes 1.30+ supports Common Expression Language (CEL) directly in ValidatingAdmissionPolicy objects without an external webhook. CEL is fast and low-overhead but limited to stateless, context-free validations. OPA and Kyverno remain necessary for policies that require external data lookups or complex mutation logic.
OPA Gatekeeper: Policy Power Through Rego
Open Policy Agent (OPA) is a graduated CNCF project and general-purpose policy engine. OPA Gatekeeper is the Kubernetes operator that integrates OPA into cluster admission control. It introduces two custom resources: ConstraintTemplate (defines a policy rule in Rego, creating a new CRD) and Constraint (an instance of a ConstraintTemplate that specifies where and how the rule applies). This separation of definition from enforcement is what makes Gatekeeper composable at enterprise scale.
Rego is a declarative, logic-based query language designed for policy evaluation. A Rego rule expresses a condition that must be true for the policy to pass. The language handles set operations, object traversal, and external data lookups natively — which is why OPA can enforce policies that reference data outside the Kubernetes API, such as an external CMDB, an IP allowlist, or a service catalog. For teams that need to enforce consistent policy logic across Kubernetes, Terraform, API gateways, and application authorization, a single Rego policy library eliminates the drift that happens when each layer maintains its own rules.
- →ConstraintTemplate: defines a Rego rule and creates a new CRD on install. Example: a RequiredLabels template defines which labels are mandatory and creates a RequiredLabels CRD that ops teams instantiate per use case.
- →Constraint: an instance of a ConstraintTemplate that scopes where the rule applies — all Namespaces cluster-wide, resources in specific namespaces, or only resources of a specific kind.
- →External data via OPA Data: Gatekeeper 3.14+ supports external data providers, allowing Rego policies to call out to an external API during admission evaluation — enabling policies like blocking an image unless it appears in a verified registry API, which is not expressible in CEL.
- →Audit mode: Gatekeeper scans existing resources against all active constraints on a configurable schedule and surfaces violations on resources that predate the constraint — critical for brownfield cluster governance and compliance reporting.
- →Policy library: the open-source OPA Gatekeeper library provides 30+ production-ready ConstraintTemplates covering Pod Security Standards, required labels, approved registries, resource limits, and host path restrictions.
Kyverno: Kubernetes-Native Policy Without a Custom Language
Kyverno is a Kubernetes-native policy engine built from the ground up for cluster admission control. Every policy is a Kubernetes resource — a ClusterPolicy or a namespaced Policy — written in YAML using Kubernetes-idiomatic patterns. There is no custom language to learn. A Kyverno ClusterPolicy has three rule types: validate (reject non-compliant resources), mutate (modify incoming resources at admission time), and generate (create additional resources when a trigger resource is created or updated).
Kyverno reached CNCF graduation in early 2026 and is now the default admission policy engine on several major managed Kubernetes distributions, including EKS Anywhere and Rancher fleet deployments. Its PolicyReport CRD integrates natively with Kubernetes observability stacks, allowing tools like Grafana and OpenSearch to query violation counts without a separate sidecar. The Kyverno CLI enables policy testing and dry-run validation locally and in CI pipelines — the same ClusterPolicy YAML that runs in the cluster runs in the pipeline, with no translation layer.
- →Validate rule: specifies conditions a resource must satisfy. Supports pattern matching, deny conditions, foreach iterations over arrays (checking every container in a pod spec), and preconditions that scope when the rule applies.
- →Mutate rule: uses strategic merge patch or JSON patch to modify resources at admission time. Common use case: adding readOnlyRootFilesystem: true to containers that omit it, so security hardening does not block new workloads during brownfield migration.
- →Generate rule: creates related Kubernetes resources automatically. Example: whenever a new Namespace is created, generate a default-deny NetworkPolicy — eliminating the manual step that teams routinely skip under pressure.
- →Background scanning: Kyverno continuously evaluates existing resources against active policies and populates PolicyReport objects with violation findings, enabling compliance monitoring beyond admission-time enforcement.
- →PolicyException: Kyverno 1.11+ supports PolicyException resources — a named, audited exemption from a specific policy for a specific resource, replacing ad-hoc annotation workarounds that are invisible to auditors.
OPA Gatekeeper vs. Kyverno: Decision Criteria for Enterprise Teams
The choice is not which engine is better in the abstract — it is which engine fits your organization's skills, compliance requirements, and infrastructure scope. Both are production-grade, CNCF-graduated projects with enterprise support contracts available. The material differences are in policy language complexity, cross-stack reuse potential, and mutation capabilities.
- →Choose OPA Gatekeeper when: your team already uses Rego for Terraform, API gateway authorization, or application-level policy (OPA + Envoy); you need policies that reference external data sources not available in the Kubernetes API; you have dedicated platform engineering capacity to manage ConstraintTemplate lifecycle; or you need a single policy language enforced consistently across Kubernetes and non-Kubernetes surfaces.
- →Choose Kyverno when: your cluster operations team is Kubernetes-fluent but does not have Rego expertise; you need generate rules to automate companion resource creation on namespace provisioning; you want PolicyReports natively integrated with your observability stack; or you are managing EKS Anywhere, Rancher, or another distribution where Kyverno is the default engine.
- →Use both when: you need Kyverno for Kubernetes-specific mutations and namespace automation, and OPA for cross-stack policy enforcement on APIs, CI/CD pipelines, and Terraform plan evaluations. This hybrid is the model recommended by the CNCF governance reference architecture for enterprises with polyglot infrastructure.
- →Operational overhead: Gatekeeper adds CRD management overhead per ConstraintTemplate — a growing policy library means a growing set of CRDs to version. Kyverno ClusterPolicies are simpler to update but require discipline on version pinning across teams. Both engines need webhook availability monitoring, since a down admission webhook configured with failurePolicy: Fail blocks all resource creation in affected namespaces.
- →Avoid premature standardization: pilot one cluster per engine, measure policy coverage and violation catch rate, then standardize from evidence rather than from vendor preference.
Shift-Left: Extending Kubernetes Policy Enforcement Into CI/CD
Admission control catches policy violations at deploy time — after a manifest has been written and a commit pushed. A manifest that violates your required-labels constraint fails silently in development, surfaces as a blocked deployment in staging, and delays an on-call engineer when it reaches production. Shift-left policy enforcement runs the same checks in CI, before the manifest ever reaches a cluster. For how this fits inside a GitOps delivery model, see our post on GitOps implementation for enterprise Kubernetes.
OPA's shift-left tool is conftest — a CLI that evaluates configuration files (YAML, JSON, HCL, Dockerfile, and more) against Rego policies locally or in CI. A conftest check on a Kubernetes manifest runs the same Rego logic that Gatekeeper evaluates at admission, giving deterministic consistency between CI and runtime enforcement. Kyverno's CLI provides equivalent functionality: kyverno apply runs ClusterPolicy YAML against a manifest directory and outputs a PolicyReport-structured result. Both integrations require no cluster access and run entirely against the local filesystem, making them safe to run on every PR build.
- →CI integration pattern: add a policy validation step after your helm template or kustomize build step, before the kubectl apply or Argo CD sync. The step fails the build on any critical violation, blocking the manifest from reaching the cluster.
- →Policy drift prevention: if your CI and runtime policies live in the same Git repository and are referenced by both the CI job and the Gatekeeper or Kyverno installation, policy drift is structurally impossible. GitOps delivery of the policy layer ensures runtime state always matches the versioned intent.
- →Developer feedback: surface policy violations as inline PR annotations rather than opaque build failure messages. Tools like Reviewdog parse conftest or Kyverno CLI output and post violation details as annotations on the specific manifest lines that failed — reducing the time to understand and fix a policy failure from minutes to seconds.
- →Performance: a conftest or Kyverno CLI check over a typical Helm chart output (50 to 200 manifests) completes in under five seconds — fast enough to run on every PR without affecting developer velocity.
Five Enterprise Policy Controls That Satisfy Auditors
Abstract governance frameworks are not what auditors examine. They examine whether specific controls are demonstrably active and whether violations are logged. Here are the five Kubernetes policy controls that enterprise security and compliance teams consistently require, with implementation notes for both engines.
- →Block privileged containers: any Pod that sets securityContext.privileged: true gets cluster-admin-equivalent access. This is a hard block in every production cluster with no exceptions. Gatekeeper: use the psp-privileged-container ConstraintTemplate from the official library. Kyverno: a validate rule with a deny condition on any container security context that sets privileged to true.
- →Require image registry allowlist: containers must only pull images from approved registries — your ECR, GCR, or Artifactory — not public Docker Hub. This is the single most impactful supply-chain security control for Kubernetes. Both engines support regex-based registry pattern matching. Absence of this policy is a common SOC 2 finding.
- →Require CPU and memory limits on every container: a container without a limits block can consume unbounded node resources and trigger cascading OOMKills across the cluster. A Kyverno mutate rule that applies sensible defaults when limits are absent is more practical than a hard block for brownfield clusters mid-migration.
- →Require labels for cost allocation: Kubernetes resource labels (team, environment, cost-center) are the input for FinOps tools like Kubecost and OpenCost. Enforce them at admission or the cost data is ungroupable. Gatekeeper's RequiredLabels ConstraintTemplate is the canonical reference implementation.
- →Namespace network isolation via generate: Kyverno generate rules create a default-deny NetworkPolicy in every new Namespace automatically, enforcing zero-trust network posture at the cluster layer without requiring every team to remember a step they routinely skip.
Frequently Asked Questions
What is Kubernetes policy as code?
Kubernetes policy as code is the practice of expressing cluster governance rules — security constraints, compliance requirements, operational standards — as versioned code that the cluster enforces automatically at admission time. Instead of documenting that containers should not run as root and trusting developers to comply, a policy as code engine intercepts every resource creation request and rejects it if the resource violates the rule. Policies live in Git, go through code review, and are deployed to clusters the same way application manifests are.
Is OPA Gatekeeper better than Kyverno for enterprise Kubernetes?
Neither is objectively better — they solve the problem differently. OPA Gatekeeper's Rego language is more powerful for complex, cross-stack policy logic and external data integration, but has a steeper learning curve. Kyverno's YAML-native policies are faster to write and operate for teams fluent in Kubernetes but not in Rego. Enterprise teams that need cross-stack policy consistency across Kubernetes, Terraform, and API gateways tend to converge on OPA. Teams that want Kubernetes-native simplicity and need generate rules for companion resource automation tend to prefer Kyverno.
How does Kubernetes admission control work with a policy engine?
When a resource is submitted to the Kubernetes API server, the server calls registered admission webhook endpoints after authentication and authorization. OPA Gatekeeper and Kyverno both operate as admission webhook servers — they receive the resource in the request body, evaluate it against all active policies, and return an admission response. If any validating webhook returns a deny decision, the API server rejects the request and returns the policy violation message to the caller. The entire round-trip takes under 100 ms for typical policy sets.
Can you run OPA Gatekeeper and Kyverno in the same cluster?
Yes. Both engines register as separate admission webhooks and operate independently — a single resource request is evaluated by both webhook chains in sequence. Configure both with appropriate failurePolicy values (Ignore for non-critical policies, Fail for security-critical ones) and size policy engine pods with adequate resource limits to prevent throttling under high pod churn. Set explicit timeoutSeconds on each WebhookConfiguration to avoid timeout cascades when one engine is under load.
How does Kubernetes policy as code support SOC 2 and ISO 27001 compliance?
Policy as code turns control requirements into auditable, machine-enforced rules. For SOC 2, the controls map to access management (RBAC policies enforced at admission), secret handling (block pods that mount raw Secrets as environment variables), and change management (policy changes require Git PRs with required reviewers). For ISO 27001 Annex A, the controls map to privileged access management (block privileged containers), vulnerability management (enforce image scanning gates as admission policies), and asset inventory (require metadata labels on every workload). Audit evidence is the policy code itself plus PolicyReport violation logs from each audit window.
How Belsoft Helps Enterprise Teams Implement Kubernetes Governance
Belsoft designs and implements Kubernetes policy-as-code frameworks for enterprise engineering teams — from policy library selection and ConstraintTemplate or ClusterPolicy authoring to CI/CD integration and audit reporting. Our security and scalability engineering practice covers the full governance stack: admission control, RBAC architecture, network policy design, and the compliance evidence collection that satisfies SOC 2 and ISO 27001 auditors.
If your clusters are operating without admission policy enforcement — or if your current policy set has grown inconsistent and untested — we run a Kubernetes governance assessment that maps your posture against your compliance requirements and delivers a prioritized remediation plan. Schedule a technical review to discuss where your cluster governance stands.
“A policy you document but do not enforce is a liability. A policy enforced at admission is a control.”
Written by
Belsoft Team
More from the blog
Ready to build?
Let's talk about your project.
30 minutes. No pitch. We map your requirements and tell you honestly what it will take.
Book a Strategy Call