

Table of Contents
See Why DevOps Leaders Choose Testkube for Continuous Testing
See Why DevOps Leaders Choose Testkube for Continuous Testing





Table of Contents
Organizations typically manage hundreds or thousands of microservices across multiple clusters, cloud providers, and environments. Each deployment introduces potential security, compliance, and operational risks that traditional manual governance approaches cannot scale to address.
This scale creates a tension: DevOps teams move fast, deploying code multiple times a day, while security and compliance teams demand rigorous reviews and approvals. The result is often a trade-off—either slowing innovation or weakening security posture. As environments evolve, configurations gradually diverge from intended standards. Regulatory frameworks such as SOC 2, PCI DSS, and GDPR require continuous demonstration of compliance. Adhering to these compliances as part of cloud-native pipelines is the only solution to identify policy violations before deployment to production, thereby avoiding costly and disruptive remediation.
Understanding Policy-as-Code (PaC) in Kubernetes
The process of managing policies in an automated and code-driven manner, such that it operates at a cloud-native scale and velocity, is known as Policy as Code. In Kubernetes, they are mostly deployed using Admission Controllers, which ensure policies are enforced on the intended resources at runtime.
With Kubernetes supporting Common Expression Language (CEL) expressions, policies can be defined that are more human-readable and resource-friendly. They can be written as YAML or Rego that declare intended outcomes rather than procedural steps. For example, "all containers must have resource limits" rather than "check each container and reject if limits are missing."
Policy-as-Code matters because security must shift left. This means catching issues early in pipelines, where fixes are faster and cheaper. Growing regulatory pressure demands continuous compliance and immutable audit trails, something manual processes can’t deliver at scale. Automated governance closes this gap by enforcing policies consistently across teams and environments, balancing speed with security and enabling cloud-native organizations to scale without sacrificing control.
Here are some of the key benefits:
- Early Feedback: Policies validate resources during development and CI/CD, catching misconfigurations before they reach production. This shift-left approach reduces remediation costs and gives developers immediate guidance with secure-by-default guardrails.
- Reduced Drift: Automated enforcement keeps running workloads aligned with defined standards, minimizing configuration drift. Continuous monitoring ensures deviations are detected and corrected in real time across clusters and environments.
- Better Auditability: Version-controlled policies and engine reports provide clear, immutable audit trails. Uniform enforcement across clusters and teams ensures reliability at scale.
Common policy frameworks
The policy-as-code landscape offers several powerful tools, each with distinct approaches to governance automation.
Open Policy Agent (OPA)
OPA is a general-purpose policy engine that implements policy-as-code across the entire cloud-native stack. Originally developed by Styra and donated to the CNCF, OPA serves as a unified policy layer that can enforce policies across microservices, Kubernetes, CI/CD pipelines, API gateways, and infrastructure components.
OPA uses Rego, a high-level declarative language specifically designed for expressing policies across complex, hierarchical data structures. Rego enables fine-grained policy logic with support for complex conditions, data transformations, and external data integration.
Kyverno
Kyverno is a cloud native policy engine purpose-built for Kubernetes and now usable beyond Kubernetes clusters as a unified policy language. Unlike traditional engines, Kyverno focuses on accessibility, letting administrators define policies entirely in YAML without needing to learn a specialized language. Policies follow Kubernetes-native patterns, reducing complexity and aligning governance with existing workflows.
Kyverno policies can validate configurations, mutate resources, generate new resources, verify container images, and automatically clean up unused objects. With no external dependencies, strong reporting through PolicyReports, and active community support, Kyverno provides a powerful, approachable way to implement Policy-as-Code at cloud native scale.
Gatekeeper
Gatekeeper is the Kubernetes-specific implementation of the Open Policy Agent (OPA), designed to bring OPA's policy capabilities directly into Kubernetes admission control. Gatekeeper bridges the gap between OPA's general-purpose policy engine and Kubernetes-specific governance requirements.
With native Kubernetes CRDs for instantiating and extending the policy library, it also has mutation support. Gatekeeper has built-in audit functionality and can integrate external data sources for richer policy evaluation.
Integrating Policy-as-Code into Kubernetes Testing Workflows
Modern Kubernetes testing pipelines must embed policy validation at every stage to ensure compliance, security, and operational excellence while maintaining development velocity.

Early stages, such as pre-commit and CI pipelines, focus on providing fast feedback through linting, unit, integration, and security checks. As changes move toward staging or ephemeral clusters, regression, functional, and performance smoke tests ensure workloads behave as expected before deployment. Finally, in production or production-like environments, continuous policy monitoring, automated regression tests, and chaos experiments validate resilience and compliance in real time.
Pre-commit hooks
PaC ensures developers get immediate feedback without needing a cluster by running lightweight checks on YAML/JSON manifests. This shifts compliance left, reducing review overhead and catching obvious misconfigurations early (e.g., missing resources or bad labels). It can integrate with tools like pre-commit or Git hooks to automatically run policies before code is pushed.
Example: The following Rego rule will deny images from untrusted image registries and only allow if the container object's "image"` field starts with "hooli.com/".
package kubernetes.validating.images
deny contains msg if {
input.request.kind.kind == "Pod"
# The `some` keyword declares local variables. This rule declares a variable
# called `container`, with the value any of the input request's spec's container
# objects. It then checks if the container object's `"image"` field does not
# start with "hooli.com/".
some container in input.request.object.spec.containers
not startswith(container.image, "hooli.com/")
msg := sprintf("Image '%v' comes from untrusted registry",
[container.image])
}
CI phase
In CI, PaC acts as a gate by validating manifests against a centralized policy set, ensuring only compliant manifests pass pipelines. Policies can enforce organization-wide standards like required labels or annotations, resource requests, or image registries.
Example: Kyverno test can be run as a part of the CI pipeline, and failures can block merges. There can be one or more policies run against multiple resources placed in a directory(For example: tests). In this Kyverno test, the policies and resources file path are passed. This policy checks if the required label is available in a resource and passes only if it exists.
apiVersion: cli.kyverno.io/v1alpha1
kind: Test
metadata:
name: require_labels_test
policies:
- ./require_labels.yaml
resources:
- ./pod_with_label.yaml
- ./pod_without_label.yaml
results:
- policy: require-labels
rule: check-for-label
resource: web-app-with-label
kind: Pod
result: pass
- policy: require-labels
rule: check-for-label
resource: web-app-without-label
kind: Pod
result: pass
This can run as part of the CI pipeline:
jobs:
kyverno_policy_test:
runs-on: ubuntu-latest
steps:
...
- name: Setup Kyverno CLI
uses: kyverno/action-install-cli@v0.2.0
with:
release: 'v1.14.4'
- name: Verify Kyverno CLI installation
run: kyverno version
- name: Test the policy against the resource
run: kyverno test ./tests
Here, `kyverno test ./tests` will execute as part of the pipeline and apply the policies on resources in the CI phase.
CD phase
At deployment time, PaC ensures only compliant resources enter the cluster by leveraging Kubernetes admission webhooks. Gatekeeper runs at the API server boundary, evaluating Constraints (policy instances) against live admission requests. This prevents “shadow IT” style deployments (like manual kubectl apply) from bypassing policy enforcement.
Example: Constraint (sketch) rejecting privileged pods:
kind: K8sPSPPrivilegedContainer
spec: { enforcementAction: deny }
Post-deployment audits & regression tests
In this phase, policies don’t just block new changes; they continuously run inside the cluster to ensure that all existing resources still comply with organizational rules. Audit controllers or periodic scans are essential to detect drift and regressions.
For example, Kyverno’s background scans or Gatekeeper’s audit controller can enumerate all Pods/Deployments in the cluster and check whether they adhere to policies like requiring labels, disallowing latest tags, or enforcing network policies. These violations can be surfaced as Kubernetes events, logged centrally, or exported as compliance reports. Kyverno generates policy reports that capture all the violations, and then these can be tracked using event-driven workflows like ArgoEvents. Any new or incoming change that does not comply with the cluster's policies can trigger tests with test orchestration tools like Testkube from the cluster.
Conclusion
Managing Kubernetes at scale requires more than ad-hoc reviews — it needs consistency, repeatability, and automation. Policy-as-Code provides exactly that by codifying security, compliance, and resource rules in a Kubernetes-native way, ensuring they can be versioned and applied across clusters.
In the next blog, we’ll see this in action with a demo that combines policies and Testkube to enforce rules and trigger automated tests directly from the cluster.
Get started with Testkube to integrate policy-driven testing into Kubernetes. Automate compliance checks, validate workloads against resource policies, and ensure application reliability with minimal overhead. Join the Testkube Slack community to start a conversation or read Testkube documentation to start building fault-tolerant, automated test pipelines tailored to the organisation’s infrastructure.


About Testkube
Testkube is a test execution and orchestration framework for Kubernetes that works with any CI/CD system and testing tool you need. It empowers teams to deliver on the promise of agile, efficient, and comprehensive testing programs by leveraging all the capabilities of K8s to eliminate CI/CD bottlenecks, perfecting your testing workflow. Get started with Testkube's free trial today.