Policy-as-Code in Practice: From Theory to Implementation with OPA and Rego
A production-grade guide to Open Policy Agent and Rego — writing, testing, and enforcing consistent policies across Kubernetes admission control, CI/CD pipelines, and Terraform infrastructure.
This article provides a hands-on deep-dive into Open Policy Agent (OPA) and its declarative policy language, Rego — covering everything from your first admission-control rule to production-grade RBAC, ABAC, CI/CD gates, and Terraform plan evaluation across multi-cloud environments.
When should I choose OPA over a cloud-native alternative?
OPA is the right choice when you need a single policy language that works across Kubernetes admission control, API gateways, CI/CD pipelines, and infrastructure-as-code tools like Terraform. Cloud-native alternatives — such as AWS Service Control Policies, Azure Policy, or GCP Organization Policies — lock you into one provider. Sentinel, HashiCorp's policy language, is limited to the Terraform ecosystem. OPA's Rego runs everywhere: as a sidecar, an admission controller via Gatekeeper, an API middleware, or a CLI gate in your pipeline. The trade-off is operational complexity; you manage the OPA deployment and policy lifecycle yourself rather than relying on a managed service.
Sources: CNCF Open Policy Agent · OPA Gatekeeper Documentation · OPA Community Survey 2025
Overview
Policy-as-code has evolved from a theoretical best practice into an operational necessity. As organizations scale across multi-cloud environments, the need for consistent, auditable, and version-controlled policy enforcement becomes non-negotiable. Open Policy Agent (OPA) — a CNCF graduated project — provides the most mature open-source framework for implementing this paradigm at scale.
In 2025, the OPA Services market was valued at $0.6 billion and is projected to reach $3.2 billion by 2034, growing at a 22.5% CAGR. The 2025 OPA Community Survey, conducted online and at KubeCon Atlanta, revealed that Kubernetes admission control, API authorization, and infrastructure validation remain the top three use cases. North America commands the largest regional share at 42.3%, driven by mature cloud adoption within BFSI institutions and stringent regulatory frameworks including NIST cybersecurity guidelines.
This article walks through OPA and Rego from first principles to production deployment — with concrete examples, testing strategies, and CI/CD integration patterns.
What is Open Policy Agent?
OPA is an open-source, general-purpose policy engine that decouples policy decision-making from application logic. Rather than embedding authorization rules inside your codebase, OPA provides a unified policy engine that can be deployed anywhere — as a sidecar, an admission controller, an API gateway plugin, or a standalone service.
Core Architecture
The following diagram shows how an application queries the OPA engine for policy decisions.
flowchart LR
Application["Application (your code)"]
OPA["OPA Engine"]
Rego["Rego Policies"]
Data["Data (JSON)"]
Application -->|query| OPA
OPA -->|decision| Application
OPA --> Rego
OPA --> Data
The engine evaluates Rego policies against structured data and returns a simple true/false decision. This simplicity is deliberate — it keeps policy evaluation fast, predictable, and testable.
Why Rego?
Rego is OPA's declarative query language. Unlike imperative languages where you define step-by-step logic, Rego lets you express what a policy should enforce and let the engine figure out how to evaluate it. Key characteristics:
- Declarative: Policies describe desired state, not execution flow
- Data-driven: Policies operate on structured JSON data
- Composable: Rules can reference other rules, enabling modular policy design
- Testable: Built-in testing framework with
__rego_test_module__annotations - Turing-complete: Can express any computable policy logic
Getting Started: Your First Rego Policy
Let's start with a concrete example. Imagine you need to enforce that all Kubernetes pods must include resource limits — a common security and cost governance requirement.
The Rego Policy
package kubernetes.admission.resources
# Deny if a container has no resource limits
deny[msg] {
input.request.object.spec.containers[_]
not input.request.object.spec.containers[_].resources.limits
msg := sprintf("Container '%v' has no resource limits defined",
[input.request.object.spec.containers[_].name])
}
# Deny if a container has no resource requests
deny[msg] {
input.request.object.spec.containers[_]
not input.request.object.spec.containers[_].resources.requests
msg := sprintf("Container '%v' has no resource requests defined",
[input.request.object.spec.containers[_].name])
}
This policy evaluates every pod creation request. If any container lacks resource limits or requests, it returns a denial message. The deny rule is the standard pattern — OPA unions all denied messages and returns them to the admission controller.
Testing the Policy
OPA includes a built-in testing framework. Here's how you'd test the above policy:
package kubernetes.admission.resources_test
import rego.v1
# Test: Pod without resource limits should be denied
deny[msg] {
input = {
"request": {
"object": {
"spec": {
"containers": [{
"name": "web",
"image": "nginx:latest"
}]
}
}
}
}
kubernetes.admission.resources.deny[msg]
}
# Test: Pod with resource limits should pass
allow {
input = {
"request": {
"object": {
"spec": {
"containers": [{
"name": "web",
"image": "nginx:latest",
"resources": {
"limits": {"cpu": "500m", "memory": "128Mi"},
"requests": {"cpu": "250m", "memory": "64Mi"}
}
}]
}
}
}
}
not kubernetes.admission.resources.deny[_]
}
Run with: opa test -v .
Rego Language Fundamentals
To write effective policies, you need to understand Rego's core constructs. Here's a practical breakdown.
Rule Definitions
Rego rules follow the pattern output[input_condition] { body }. The rule evaluates to true if the body can be satisfied, and returns computed values from expressions in the body.
# Simple boolean rule
allow {
input.user.role == "admin"
}
# Rule that computes a value
role_level[level] {
input.user.role == "admin"
level := 3
}
role_level[level] {
input.user.role == "viewer"
level := 1
}
Set Operations and Comprehensions
Rego excels at set operations — a natural fit for policy evaluation where you're often checking membership across collections.
# Check if any container image uses a blocked registry
blocked_image {
image := input.request.object.spec.containers[_].image
blocked_registry := ["docker.io/untrusted", "gcr.io/compromised"]
some i
blocked_registry[i] == image
}
# Using set comprehension for allowed registries
allowed_registries := {"gcr.io/prod", "registry.internal", "ghcr.io/org"}
# Check if all images come from allowed registries
all_images_allowed {
images := {img | img = input.request.object.spec.containers[_].image}
allowed_registries := {"gcr.io/prod", "registry.internal", "ghcr.io/org"}
images <= {reg + "/" + _ | reg := allowed_registries[_]}
}
Built-in Functions
OPA provides extensive built-in functions for string manipulation, data access, and logical operations:
input.request.object— the Kubernetes resource being evaluateddata.inventory.namespace[ns]— external data from your policy storesprintf("message %v", [var])— formatted stringscontains(str, substr)— substring matchingsomequantifier — existential checking
Advanced Patterns: RBAC and ABAC in Rego
Role-Based Access Control (RBAC)
OPA can enforce fine-grained RBAC across your infrastructure. Here's a policy that checks if a user has permission to perform an action on a resource:
package authz.rbac
import rego.v1
# Permission model: role -> actions -> resources
permission["admin"] = {"actions": ["read", "write", "delete"], "resources": ["*"]}
permission["developer"] = {"actions": ["read", "write"], "resources": ["staging/*"]}
permission["viewer"] = {"actions": ["read"], "resources": ["*"]}
# Check if user has permission
allow {
role := input.user.roles[_]
perms := permission[role]
action := input.action
resource := input.resource
some a
perms.actions[a] == action
resource_matches(perms.resources[_], resource)
}
# Wildcard and prefix matching for resources
resource_matches(pattern, resource) {
pattern == "*"
}
resource_matches(pattern, resource) {
startswith(resource, pattern)
}
Attribute-Based Access Control (ABAC)
For more granular control, ABAC evaluates policies against user, resource, and environmental attributes:
package authz.abac
import rego.v1
# Time-based access control
allow {
time := time.now_ns()
hour := time.hour_from_nano(time)
hour >= 8
hour <= 20
input.user.role == "developer"
input.environment != "production"
}
# Sensitive resource requires elevated clearance
allow {
input.resource.classification == "confidential"
input.user.clearance >= 3
input.user.mfa == true
}
# Resource classification levels
clearance_level["junior"] := 1
clearance_level["senior"] := 2
clearance_level["lead"] := 3
clearance_level["architect"] := 4
allow {
clearance_level[input.user.role] >= input.resource.required_clearance
}
OPA Gatekeeper: Kubernetes-Native Policy Enforcement
OPA Gatekeeper is the Kubernetes-native extension of OPA. It wraps Rego policies in Custom Resource Definitions (CRDs), enabling policy management through standard kubectl commands.
Architecture
The following diagram shows how Gatekeeper integrates with the Kubernetes API server as an admission controller.
flowchart LR
Kubectl["kubectl / k8s API Server"]
Gatekeeper["OPA Gatekeeper Admission Controller"]
ConstraintTemplate["ConstraintTemplate"]
Constraint["Constraint"]
Kubectl -->|webhook| Gatekeeper
Gatekeeper -->|allow / reject| Kubectl
Gatekeeper -->|evaluates| ConstraintTemplate
Gatekeeper -->|applies| Constraint
Gatekeeper introduces two CRD types:
- ConstraintTemplate: Defines the Rego logic and parameterized schema once
- Constraint: Instantiates the template with specific parameters for your cluster
Example: Enforcing Image Registry Policy
Step 1: Define the ConstraintTemplate
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8sallowedregistries
spec:
crd:
spec:
names:
kind: K8sAllowedRegistries
validation:
openAPIV3Schema:
type: object
properties:
registries:
type: array
items:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sallowedregistries
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
not startswith(container.image, input.parameters.registries[_])
msg := sprintf(
"Container '%v' uses unauthorized image registry: %v",
[container.name, container.image])
}
Step 2: Apply the Constraint
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedRegistries
metadata:
name: restrict-registries
spec:
enforcementAction: deny
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
parameters:
registries:
- "gcr.io/prod-project"
- "registry.internal.company.com"
- "ghcr.io/our-org"
Now any pod creation that references an image from an unauthorized registry will be rejected by the admission webhook.
Enforcement Modes
Gatekeeper supports three enforcement modes:
| Mode | Behavior | Use Case |
|---|---|---|
deny |
Blocks non-compliant requests | Production security policies |
dryrun |
Logs violations but allows | Policy testing before enforcement |
audit |
Only logs to audit log | Compliance monitoring |
Switch between modes without changing policy logic — a critical feature for gradual rollout.
CI/CD Integration: Policy Gates
OPA's most powerful CI/CD integration comes through its CLI and decision logging capabilities. Policies can act as gates in your pipeline, preventing non-compliant deployments from reaching production.
OPA as a CI/CD Gate
# .github/workflows/policy-check.yml
name: Policy-as-Code Gate
on:
pull_request:
paths:
- 'k8s/**'
- 'terraform/**'
jobs:
policy-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install OPA
run: |
curl -LO "https://openpolicyagent.org/downloads/v0.68.0/opamd_0.3.1_linux_x86_64.tar.gz"
tar -xzf opamd_0.3.1_linux_x86_64.tar.gz
sudo mv opamd /usr/local/bin/
- name: Run Rego Policy Tests
run: opa test ./policies --fail
- name: Evaluate Terraform Plan
run: |
tfplan=$(terraform plan -out=tfplan -no-color 2>&1)
echo "$tfplan" > /tmp/plan.txt
opa eval \
-i tfplan.json \
-d ./policies \
"data.terraform.deny"
- name: Evaluate Kubernetes Manifests
run: |
for manifest in k8s/**/*.yaml; do
k8s_input=$(cat "$manifest" | jq '{request: {object: .}}')
opa eval \
-i "$k8s_input" \
-d ./policies/kubernetes \
"data.kubernetes.deny"
done
Terraform Plan Evaluation
OPA can evaluate Terraform plans before they're applied, catching policy violations before infrastructure changes take effect. This is the "shift-left" approach to policy enforcement.
# policies/terraform.rego
package terraform
import rego.v1
# Deny if a security group allows unrestricted ingress
deny[msg] {
resource := input.resource_changes[_]
resource.change.after.type == "aws_security_group"
ingress := resource.change.after.ingress[_]
ingress.cidr_blocks[_] == "0.0.0.0/0"
ingress.from_port == 0
msg := sprintf("Security group '%v' allows unrestricted ingress on port %v",
[resource.address, ingress.from_port])
}
# Deny if storage is unencrypted
deny[msg] {
resource := input.resource_changes[_]
resource.change.after.type == "aws_s3_bucket"
not resource.change.after.server_side_encryption_configuration
msg := sprintf("S3 bucket '%v' has no server-side encryption", [resource.address])
}
# Deny if a database is publicly accessible
deny[msg] {
resource := input.resource_changes[_]
resource.change.after.type == "aws_db_instance"
resource.change.after.publicly_accessible == true
msg := sprintf("RDS instance '%v' is publicly accessible", [resource.address])
}
Sentinel vs OPA: A Quick Comparison
HashiCorp's Sentinel (built into Terraform Cloud/Enterprise) and OPA serve similar purposes but with different philosophies:
| Aspect | OPA + Rego | HashiCorp Sentinel |
|---|---|---|
| Scope | Multi-cloud, multi-tool | Terraform-centric |
| Language | Declarative (Rego) | Imperative (HCL-like) |
| Testing | Built-in framework | Limited |
| Portability | Policies work across K8s, APIs, CI/CD | Terraform-specific |
| Community | Large, CNCF-backed | Smaller, HashiCorp-focused |
| Cost | Open source, self-hosted | Enterprise-only |
For organizations already using OPA for Kubernetes policies, extending it to Terraform creates a unified policy language across the entire stack.
Design Patterns for Production Policy-as-Code
The CNCF's 2025 guidance on secure OPA deployment identified seven best practices. Here's how they translate into actionable patterns.
Pattern 1: Separate Policy Code from Application Code
Policies live in their own repository or at minimum a dedicated policies/ directory — never embedded in application source code. This separation enables:
- Independent review workflows for policy changes
- Dedicated policy owners (SRE, security, or platform teams)
- Reusable policies across multiple services
- Audit trails separate from application history
repo-root/
├── policies/
│ ├── kubernetes/
│ │ ├── admission/
│ │ │ ├── resources.rego
│ │ │ └── registries.rego
│ │ └── audit/
│ │ └── labels.rego
│ ├── terraform/
│ │ └── security.rego
│ └── authz/
│ ├── rbac.rego
│ └── abac.rego
├── k8s/
├── terraform/
└── src/
Pattern 2: Decouple Schema and Data
Policies should reference data through the data package, not hardcode values. This makes policies reusable across environments:
# Good: Policy references external data
package kubernetes.admission.labels
deny[msg] {
not input.request.object.metadata.labels["app.kubernetes.io/name"]
msg := "Missing required label: app.kubernetes.io/name"
}
# Data is loaded separately via OPA's data package
# data.inventory.required_labels["Pod"] = ["app.kubernetes.io/name", "team"]
Pattern 3: Secure the Agent Itself
When deploying OPA as a sidecar or admission controller, harden the deployment:
- Run OPA pods with minimal RBAC (read-only access to policies)
- Use TLS for all OPA communication
- Enable OPA's decision logging for audit trails
- Restrict network policies to allow only authorized services to query OPA
- Rotate OPA's TLS certificates regularly
Pattern 4: Store Policy Code Securely Through GitOps
The CNCF explicitly recommends GitOps for policy code storage. This aligns with your own infrastructure approach using CDKTF and Argo CD.
# Argo CD Application for policy sync
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
name: opa-policies
spec:
project: security
source:
repoURL: https://github.com/org/policy-repo.git
targetRevision: main
path: policies/kubernetes
destination:
server: https://kubernetes.default.svc
namespace: gatekeeper-system
syncPolicy:
automated:
prune: true
selfHeal: true
Pattern 5: CI/CD and Branching Mechanisms for Policies
Policies need the same review discipline as application code. Implement a branching strategy:
- Feature branch: Write new policy or modify existing rules
- OPA test suite: Run
opa test— all tests must pass - Dry-run deployment: Apply constraints in
dryrunmode in staging - Review period: Monitor for false positives over 48-72 hours
- Enforcement switch: Change
enforcementActionfromdryruntodeny - Production rollout: Deploy to production with full enforcement
Pattern 6: Use Well-Defined Permission Models
OPA's strength is expressing permission models declaratively. For complex organizations, combine RBAC and ABAC:
package authz.combined
import rego.v1
# Role definitions
roles["admin"] = {"level": 4, "environments": ["dev", "staging", "prod"]}
roles["lead"] = {"level": 3, "environments": ["dev", "staging", "prod"]}
roles["senior"] = {"level": 2, "environments": ["dev", "staging"]}
roles["junior"] = {"level": 1, "environments": ["dev"]}
# Resource classification
resource_classifications["public-api"] = 1
resource_classifications["internal-service"] = 2
resource_classifications["customer-data"] = 3
resource_classifications["financial-records"] = 4
# Combined RBAC + ABAC decision
allow {
role := input.user.roles[_]
user_level := roles[role].level
env := input.environment
resource_class := resource_classifications[input.resource.type]
# User's role grants access to the environment
roles[role].environments[_] == env
# User clearance level meets or exceeds resource classification
user_level >= resource_class
}
The 2025 OPA Community Survey: Key Findings
The 2025 OPA Community Survey, conducted online and at KubeCon Atlanta, provides a snapshot of how OPA is used in production:
Top Use Cases (by adoption)
- Kubernetes Admission Control — Still the dominant use case, with Gatekeeper being the primary deployment method
- API Authorization — Growing rapidly as organizations move toward service mesh architectures
- Infrastructure Validation — Terraform plan evaluation and CloudFormation policy checks
- CI/CD Pipeline Gates — Policy-as-code acting as quality gates before deployments
- Data Access Control — Fine-grained authorization for data platforms and analytics
Key Trends
- North America leads at 42.3% of OPA services market revenue, driven by BFSI institutions and technology giants with stringent regulatory requirements
- Regulatory pressure is a major adoption driver — NIST cybersecurity guidelines, SOC 2 compliance, and industry-specific regulations are pushing organizations toward policy-as-code
- OPA Gatekeeper adoption continues to grow within the Kubernetes ecosystem, with most new deployments using the latest ConstraintTemplate/Constraint pattern rather than raw OPA sidecars
Testing Strategies for Policy-as-Code
Writing policies is only half the challenge. Ensuring they work correctly at scale requires rigorous testing.
Unit Testing with OPA's Built-in Framework
OPA's test framework uses a naming convention: any file ending in _test.rego is automatically discovered and executed.
package kubernetes.admission.resources_test
import rego.v1
# Test table approach: parameterized tests
deny[msg] {
input = {
"request": {
"object": {
"spec": {
"containers": [{
"name": test_container_name,
"image": test_image,
}]
}
}
}
}
kubernetes.admission.resources.deny[msg]
}
# Provide test data via table-driven approach
test_container_name = "web"
test_image = "nginx:latest"
Integration Testing with OPA's HTTP API
OPA exposes an HTTP API for evaluating policies against arbitrary data — perfect for integration tests.
#!/bin/bash
# integration_test.sh
# Test 1: Pod without resource limits should be denied
curl -s -X POST http://localhost:8181/v1/data/kubernetes/admission/resources/deny \
-H "Content-Type: application/json" \
-d '{
"input": {
"request": {
"object": {
"spec": {
"containers": [{"name": "web", "image": "nginx"}]
}
}
}
}
}' | jq '.result | length > 0'
# Test 2: Pod with resource limits should pass
curl -s -X POST http://localhost:8181/v1/data/kubernetes/admission/resources/deny \
-H "Content-Type: application/json" \
-d '{
"input": {
"request": {
"object": {
"spec": {
"containers": [{
"name": "web",
"image": "nginx",
"resources": {
"limits": {"cpu": "500m", "memory": "128Mi"}
}
}]
}
}
}
}
}' | jq '.result | length == 0'
Policy Drift Detection
Monitor for policy drift by comparing the live OPA policy bundle against the Git repository:
# Fetch current policy bundle from OPA
curl -s http://localhost:8181/v1/policies > /tmp/current_bundle.json
# Compare with Git version
git diff --quiet HEAD -- policies/ || echo "Policy drift detected!"
Performance Considerations
OPA is designed for low-latency policy evaluation, but understanding its performance characteristics helps you design effective architectures.
Decision Latency Benchmarks
| Deployment Mode | Typical Latency | Throughput |
|---|---|---|
| Sidecar (local) | < 1ms | 10,000+ decisions/sec |
| Standalone service | 5-20ms | 1,000-5,000 decisions/sec |
| Admission controller (K8s) | 50-200ms | 100-500 decisions/sec |
Optimization Techniques
- Use compiled policies:
opa build -t wasmfor WebAssembly deployment — significantly faster than interpreted evaluation - Cache external data: OPA supports data caching via the
datapackage — avoid redundant API calls in policy evaluation - Minimize
any/allquantifiers: These can cause exponential evaluation in complex policies — prefer explicit iteration - Use
__rego_metadata__for policy versioning: Track which policy version is deployed and evaluate consistently
Conclusion: Building a Policy-as-Code Practice
Policy-as-code with OPA and Rego is not just about writing rules — it's about establishing a governance practice that scales with your organization. The key takeaways:
- Start small: Begin with 2-3 high-impact policies (resource limits, image registries, labels) and expand from there
- Test everything: Use OPA's built-in testing framework religiously — policy bugs can block entire deployment pipelines
- GitOps for policies: Store all policy code in version-controlled repositories with the same review discipline as application code
- Shift-left enforcement: Evaluate policies against Terraform plans and Kubernetes manifests before they reach production
- Unified language: Rego across Kubernetes, CI/CD, and infrastructure creates a consistent governance layer
The 2025 OPA Community Survey data confirms what practitioners already know: policy-as-code is no longer optional for organizations managing complex, multi-cloud infrastructure. With OPA's CNCF-backed maturity, Rego's expressive power, and Gatekeeper's Kubernetes-native integration, the foundation for a production-grade policy practice is solid and ready to deploy.
The investment in learning Rego pays dividends across your entire stack — from admission control to CI/CD gates to API authorization. And unlike vendor-specific policy solutions, OPA's open-source nature means your policies remain portable, auditable, and under your control.