Table of contents
If you have ever written the same access control rule three separate times because Kubernetes, your API gateway, and your Terraform pipeline each require a different syntax, you already understand the problem OPA was built to solve. The logic is identical across all three. The enforcement mechanism is not. That gap is where misconfigurations happen, audits fail, and incident response slows down.
Key takeaways
- Open Policy Agent (OPA) is an open-source policy engine that evaluates authorization decisions using Rego policies decoupled from application code.
- OPA centralizes policy logic across Kubernetes admission control, API gateways, Terraform pipelines, and other systems by using a single language and evaluation engine.
- Rego is a declarative policy language designed to evaluate structured data such as JSON inputs and return structured decisions.
- OPA integrates with Kubernetes through Gatekeeper, a validating admission webhook used to enforce policies before resources are admitted.
- OPA serves as a pre-deployment gate in CI/CD pipelines to evaluate infrastructure-as-code changes such as Terraform plans before deployment.
- Best practices for OPA include mapping policies to specific compliance controls, using modular Rego packages, and enabling decision logging for audits.
- Organizations monitor OPA performance with Prometheus metrics and regularly review and test policies to maintain enforcement accuracy over time.
Open Policy Agent (OPA) explained
Open Policy Agent (OPA) is an open-source, general-purpose policy engine that decouples authorization decisions from application code, evaluating structured queries against rules written in its native language Rego and returning structured decisions any system can act on.
OPA was accepted into the Cloud Native Computing Foundation (CNCF) on March 29, 2018, moved to the incubating maturity level on April 2, 2019, and reached graduated status on January 29, 2021. CNCF lists OPA as a graduated project, the foundation’s highest maturity level.
OPA evaluates policy decisions by receiving structured input from a calling service via its API, evaluating that input against Rego policies combined with any external data provided at request time, and returning a structured JSON response. The response is typically an allow or deny decision, but OPA can return any structured data type required by the system.
Why is OPA important?
OPA solves policy fragmentation across cloud infrastructure. A security team managing AWS IAM, Kubernetes admission control, and Terraform configurations typically writes policy logic in three different syntaxes maintained by different systems. NIST SP 800-144 (Guidelines on Security and Privacy in Public Cloud Computing) identifies fragmented policy enforcement as a key risk in cloud environments.
OPA helps reduce policy fragmentation across cloud infrastructure by providing a single policy language and evaluation engine across systems that would otherwise require separate policy implementations.
For compliance teams, maintaining consistent enforcement across environments is a common challenge in SOC 2 audits and CIS Benchmark-aligned security programs. OPA addresses this with one policy language and one evaluation engine that integrates with each system. The same Rego file governing Kubernetes admission control can govern API gateway authorization and CI/CD pipeline gates, evaluated by the same engine with consistent semantics and decision logging.
Benefits and applications of OPA
Security and compliance
OPA can centralize authorization logic, which helps reduce drift between policy intent and actual enforcement. When access control rules live inside individual services, each service can become a separate place where policy behavior must be reviewed, tested, and audited.
OPA’s decision logs can provide useful evidence for access-control and compliance reviews because they record policy queries, inputs, results, timestamps, decision IDs, and bundle metadata. For Kubernetes admission controllers, teams should map policies to the benchmark versions, compliance requirements, or internal standards they are intended to enforce.
In CI/CD pipelines, OPA can function as a pre-deployment gate by evaluating Terraform plan JSON before changes are applied. For example, a team can write Rego policies that reject risky infrastructure changes before they reach production, such as public network exposure or unsafe IAM changes.
Flexibility and scalability
OPA runs as a standalone daemon (opa run), as a Go library embedded directly in an application, or as a sidecar container in Kubernetes. The same policy engine governing API authorization at the application layer can govern admission control at the Kubernetes layer using the same Rego rules and the same evaluation semantics.
For high-throughput environments, OPA supports partial evaluation, which pre-computes portions of policy logic at load time rather than per request. It can run as a standalone daemon, embedded library, or sidecar container. Performance varies by policy complexity and evaluation context, and should be measured using built-in profiling and benchmarking tools.
OPA integrates natively with OpenTelemetry for metrics and tracing. A policy evaluation running at 200ms is a latency problem, not just a policy problem. You need to see it in the same observability pipeline as the rest of your infrastructure.
Decoupling policy from code
When authorization logic lives inside application code, a policy change requires a code review, a build pipeline run, and a full deployment cycle. For something as operationally sensitive as which service accounts can call your payment processing API, that cycle is too slow and carries unnecessary risk.
With OPA, the policy is a separate artifact, a .rego file, that updates independently of the application. The application calls OPA’s API, receives a decision, and acts on it. The application code has no knowledge of the policy logic. This is the policy as code principle applied at the enforcement layer.
In practice this means a security team can immediately revoke access for a specific service account after an incident, without coordinating a deployment with the engineering team.
How does OPA work?
OPA evaluates queries using three inputs: the policy, the data, and the query input. Policies are Rego rules defining what is allowed, denied, or returned. Data provides external context such as user attributes or resource metadata. The input is the structured decision request from the calling service.
Here is a concrete example. A Kubernetes admission controller can send this query-shaped input to OPA:
{
"input": {
"request": {
"object": {
"spec": {
"containers": [
{ "name": "app", "securityContext": { "runAsNonRoot": false } }
]
}
}
}
}
}
OPA can evaluate this input against a policy requiring non-root containers and produce a structured decision document, for example:
{ "allow": false, "deny": ["Container 'app' must not run as root"] }When decision logging is enabled, OPA can log fields such as the input, result, timestamp, decision ID, queried policy path, labels, and bundle metadata. The admission controller or integration then enforces the result rather than embedding the policy logic directly.
OPA integrates with Kubernetes through Gatekeeper, a validating and mutating admission webhook that enforces CRD-based policies executed by OPA. Gatekeeper provides constraint templates, constraints, audit functionality, and a sample policy library for Kubernetes policy enforcement.
Understanding Rego
Rego is OPA’s native policy language: an open-source, declarative language for expressing authorization and policy rules across any structured data format.
Rego is built on Datalog, a subset of Prolog used in database query engines, extended to handle hierarchical JSON data structures. Datalog semantics guarantee that rule evaluation is deterministic and always terminates, which is a hard requirement for a system making access control decisions in real time. The complete Rego policy language specification is available in the OPA documentation.
Three properties define how Rego performs in production:
Expressiveness. Rego can express a four-line rule enforcing CIS Kubernetes Benchmark Control 5.2.6 or a multi-condition rule mapping PCI-DSS network segmentation requirements across an entire namespace topology. Same language, same evaluation engine.
Declarative syntax. Policies in Rego describe what is true under what conditions, not a sequence of imperative steps to compute it. This makes policies significantly easier to audit, peer-review, and test than procedural authorization logic embedded inside application code.
Flexibility with data types. Rego natively handles JSON and YAML. The same language can evaluate Kubernetes manifests, Terraform plans, API gateway request objects, and OCI image metadata. That data-type flexibility is what makes OPA genuinely reusable across environments rather than only theoretically portable.
Best practices
1. Define clear policy goals
Before writing a line of Rego, map each policy to a named compliance control: CIS Benchmark, NIST 800-53, PCI-DSS, or a documented internal standard. A policy without a named control is hard to audit and harder to justify when an engineering team asks why their deployment was blocked at 2am.
The most durable policies are typically written in response to a specific incident or compliance requirement. “Deny containers running as root because CIS Kubernetes Benchmark v1.9 Control 5.2.6 requires it” is a policy that survives team turnover and audits. “Enforce security best practices” is not a policy. It is a goal that nobody can evaluate or enforce.
2. Use modular policy design
A single Rego file handling Kubernetes admission control, Terraform plan validation, and API gateway authorization simultaneously is a maintenance problem. It is harder to test because unit tests for one enforcement context will not cover edge cases in another, and harder to debug when a policy change breaks something unexpected in a different system.
Structure policies as separate packages with scoped responsibilities. For Kubernetes-heavy environments, most teams prefer separate packages for admission, networking, rbac, and workloads, each importing shared helper rules from a lib package. The OPA Gatekeeper library follows this pattern and is worth studying as a reference for how the structure scales across a real policy library.
3. Optimize for performance
OPA evaluation is fast in most environments, but high-throughput systems can surface bottlenecks when policies traverse full documents unnecessarily. Enable partial evaluation when the same base data, such as a list of approved container registries, is evaluated against thousands of incoming admission requests per minute.
Monitor evaluation latency through OPA’s Prometheus metrics endpoint at /metrics. In Kubernetes admission control, timeout behavior depends on webhook configuration and failure policy settings. Test both latency and failure scenarios before putting any admission webhook into production.
4. Implement logging and monitoring
Enable OPA’s decision logging from day one, not as a retroactive compliance measure added before an audit. The decision log captures every evaluation: the input data, the policy decision, the policy version that produced it, and the timestamp. That record is your evidence that a specific control was enforced at the time of a specific request.
Forward decision logs to your SIEM. For environments subject to SOC 2 or PCI-DSS, the decision log provides the control evidence for CC6.1 and Requirement 7. Without it, the policy exists in your repository but the enforcement history does not exist in your audit trail. Auditors will ask for both.
5. Regularly review and update policies
A policy written two years ago and never reviewed is a policy you cannot trust. Container registry allowlists change when organizations add or remove vendors. CIS Kubernetes Benchmark v1.9 superseded v1.8 with updated Pod security standard controls, and any policy written against the older version no longer enforces the current standard even though it will still evaluate and return decisions without errors.
Build policy review into your infrastructure change management cycle. Treat .rego files with the same review standards as application code: pull requests, peer review, automated unit tests with opa test, and version-pinned deployments tracked in your change log.
OPA and Orca Security
Orca Security’s SideScanning technology provides visibility into cloud assets and configurations without requiring agents on individual workloads. Organizations can use policy-as-code frameworks such as OPA alongside cloud security programs to help define, evaluate, and enforce infrastructure standards.
This visibility helps security teams identify cloud risks, misconfigurations, and compliance gaps across their environments. Policy-as-code approaches can then be used to codify security requirements and evaluate infrastructure against defined standards throughout the development and deployment lifecycle.
For compliance reporting, Orca provides mappings to frameworks such as CIS Benchmarks, PCI DSS, HIPAA, GDPR, SOC 2, and other standards. By connecting cloud findings to specific compliance requirements, security teams can prioritize remediation efforts and better understand the potential impact of identified risks.
Frequently Asked Questions
Open Policy Agent (OPA) is an open-source policy engine that evaluates rules written in Rego and returns authorization, compliance, or policy decisions to other systems. By separating policy logic from application code, OPA helps organizations manage and enforce policies consistently across cloud-native environments.
OPA is used to implement policy as code across Kubernetes, API gateways, Terraform pipelines, CI/CD workflows, and cloud infrastructure. Security and platform teams use OPA to enforce access controls, validate infrastructure changes, support compliance requirements, and apply consistent governance across multiple environments.
OPA receives structured input from a calling system, evaluates that input against Rego policies and any relevant external data, and returns a decision. Depending on the use case, the result may be an allow/deny response, a compliance finding, or another structured output that the calling service can act upon.
Rego is OPA’s declarative policy language. It allows teams to define rules for structured data such as Kubernetes admission requests, Terraform plan outputs, API requests, and other JSON-based inputs. Because policies are written separately from application code, they can be reviewed, tested, and updated independently.
OPA Gatekeeper is a Kubernetes admission controller that uses OPA to enforce policies before resources are admitted to a cluster. It provides features such as constraint templates, policy auditing, and reusable policy libraries, making it one of the most common ways to apply OPA in Kubernetes environments.
