What is Open Policy Agent (OPA)? Policy as code with Rego, from Kubernetes to Terraform
Learn what Open Policy Agent is, how to write policies in Rego v1, how to use it beyond Kubernetes (APIs, Terraform with Conftest, Envoy), and how to enforce rules in the cluster with Gatekeeper, ConstraintTemplate, and Constraint.
Kubernetes$ opa eval -d policy.rego -i input.json "data.httpapi.authz.allow"▍Who can call this endpoint? Can this bucket be public? Can this Pod run as root? In almost every company, the answers are scattered across if statements in application code, wikis, and the heads of whoever reviews PRs. Open Policy Agent proposes a different approach: pull those decisions out of application code and write them as versioned, tested, and reviewed policy, in a language built just for that.
What Open Policy Agent is
OPA is an open source (Apache 2.0) general-purpose policy engine. It receives a question in JSON (the input), evaluates policies written in Rego together with supporting data (data), and returns a decision, also in JSON. OPA knows nothing about HTTP, Kubernetes, or Terraform: whoever integrates it decides the shape of the input and what to do with the answer.
The project was accepted into the CNCF in 2018 and has been graduated since January 2021, which is still its status as of November 2026 (check the project page). The current line is 1.x; the latest version we saw on the releases page was v1.22.4, from November 2026.
What problem it solves
- Duplicated decisions: the same rule (“only the owner can edit”) reimplemented in every service, each with a different bug.
- Ownerless rules: policy that lives in application code only changes with an application deploy.
- Hard audits: answering “why was this access denied?” means reading code. OPA records decision logs with the input, policy, and result.
- A different tool for every layer: with OPA, the same language serves Kubernetes admission control, Terraform plan review, and API authorization.
How it works
The core idea is decoupling: the service asks, OPA decides, the service enforces.
| Piece | Role |
|---|---|
input |
The context of the question: user, method, path, Kubernetes object, Terraform plan |
data |
Supporting data: team hierarchy, permission lists, settings |
| Rego policy | Declarative rules that produce the decision |
| Decision | JSON response: a true/false, a list of violations, or a full object |
| Bundles | Packages of policies and data that OPA downloads from an HTTP server or registry |
| Decision logs | A record of every decision, for auditing and debugging |
OPA runs as a server (REST), as a sidecar, as a Go library, or embedded in other tools such as Conftest and Gatekeeper.
Rego v1: if and contains
Since OPA 1.0, Rego v1 syntax is the default: the if, contains, in, and every keywords are part of the language and need no import. Rules with a body require if, and rules that build sets (such as a list of violations) require contains. Old v0-style policies (deny[msg] { ... }) don’t compile without compatibility mode. v1.22 also added an optional import rego.v2, which enables and/or; you don’t need it for anything in this article.
An example authorizing a salary HTTP API:
package httpapi.authz
default allow := false
# any authenticated person can read their own salary
allow if {
input.method == "GET"
input.path == ["salaries", input.user]
}
# managers can read the salaries of their direct reports
allow if {
input.method == "GET"
input.path[0] == "salaries"
input.path[1] in data.reports[input.user]
}
The two allow rules act as an “or”: one being true is enough. The default ensures the answer is false, not undefined, when none matches.
Hands-on example
OPA isn’t installed in the environment where this article was written, so the opa and conftest commands below follow the official documentation and weren’t run here. The Kubernetes manifests were validated against a real cluster.
Evaluating and serving the policy
# evaluate a decision locally
opa eval -d policy.rego -d data.json -i input.json "data.httpapi.authz.allow"
# format, check, and test (*_test.rego files)
opa fmt -w .
opa check policy.rego
opa test . -v
# run OPA as a REST server
opa run --server --addr :8181 policy.rego data.json
# the service asks OPA via POST /v1/data/<package>/<rule>
curl -s -X POST localhost:8181/v1/data/httpapi/authz/allow \
-d '{"input": {"method": "GET", "path": ["salaries", "ana"], "user": "ana"}}'
# {"result":true}
In production, the service calls a local OPA (a sidecar or a daemon on the same node) to keep latency low, and policies arrive through bundles, not hand-copied files.
Terraform with Conftest
Conftest uses the OPA engine to test configuration files: YAML, JSON, HCL, Dockerfiles, and more. By default it looks for deny, violation, and warn rules in the main package. For Terraform, the most reliable path is testing the plan as JSON:
package main
deny contains msg if {
some rc in input.resource_changes
rc.type == "aws_instance"
not rc.change.after.tags.owner
msg := sprintf("%s: the 'owner' tag is required", [rc.address])
}
terraform plan -out tfplan
terraform show -json tfplan > tfplan.json
conftest test tfplan.json --policy policy/
Envoy
The OPA-Envoy plugin adds a gRPC server to OPA that implements Envoy’s External Authorization API. Envoy sends the attributes of each request (method, path, headers) and OPA answers whether it may pass. The default decision path is envoy/authz/allow, and the response can be a boolean or an object with allowed, headers, and an HTTP status. The documentation recommends running OPA as a sidecar next to Envoy.
Kubernetes with Gatekeeper
Gatekeeper is OPA’s Kubernetes subproject: an admission webhook that evaluates every object creation or change. It splits a policy into two parts. The ConstraintTemplate holds the Rego and defines a new CRD; the Constraint is an instance of that CRD, with scope and parameters. Starting with Gatekeeper 3.19, Rego v1 is opt-in, enabled with version: "v1" in code[].source:
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8srequiredlabels
spec:
crd:
spec:
names:
kind: K8sRequiredLabels
validation:
openAPIV3Schema:
type: object
properties:
labels:
type: array
items:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
code:
- engine: Rego
source:
version: "v1"
rego: |
package k8srequiredlabels
violation contains {"msg": msg, "details": {"missing_labels": missing}} if {
provided := {label | input.review.object.metadata.labels[label]}
required := {label | some label in input.parameters.labels}
missing := required - provided
count(missing) > 0
msg := sprintf("missing required labels: %v", [missing])
}
---
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: namespace-requires-owner
spec:
enforcementAction: deny
match:
kinds:
- apiGroups: [""]
kinds: ["Namespace"]
parameters:
labels: ["owner"]
With this, a Namespace without the owner label is rejected. This one passes:
apiVersion: v1
kind: Namespace
metadata:
name: payments
labels:
owner: payments-team
Start with enforcementAction: dryrun or warn to see existing violations without blocking anyone, and only then switch to deny. Gatekeeper also runs a periodic audit of the objects that already exist in the cluster.
When to use it (and when not to)
Use it when you need a single policy language across several layers (cluster, IaC, APIs), when authorization rules repeat across many services, or when auditing decisions is a requirement.
Avoid or postpone it when:
- policies are few and Kubernetes-only: the native ValidatingAdmissionPolicy or Kyverno have a gentler learning curve;
- the problem is “who can access which object” with millions of relationships, as in document sharing: a ReBAC system such as OpenFGA fits better;
- nobody on the team will maintain Rego. Policy without tests and without an owner becomes yet another source of incidents.
Alternatives
| Tool | Language | Scope | Where it shines |
|---|---|---|---|
| OPA + Gatekeeper | Rego | General (K8s, IaC, APIs) | One language for everything, complex policies |
| Kyverno | YAML + CEL | Kubernetes | Teams that would rather not learn Rego |
| ValidatingAdmissionPolicy | CEL | Kubernetes (native) | Simple validations, no extra webhook |
| OpenFGA | Model DSL + tuples | Application authorization | Relationship-based permissions at scale |
For the full picture of cluster security, where admission control is just one layer, see Kubernetes cluster hardening.
Summary
- OPA is a general-purpose policy engine: it takes JSON
inputand returns a decision - It’s a graduated CNCF project; check the current status on the project page
- Use Rego v1 (
if,contains,in), the default since OPA 1.0 - Test policies with
opa testand distribute them with bundles, not manual copies - Conftest brings the same rules to Terraform, YAML, and Dockerfiles in CI
- In Gatekeeper, the ConstraintTemplate holds the Rego and the Constraint holds scope and parameters
- Start with
dryrun/warnand only then block withdeny
Policy that only exists in a PR reviewer’s head doesn’t scale; policy as code does.