What Open Policy Agent is, how Rego works, and how to evaluate a Terraform JSON plan with opa eval, opa test and Conftest before apply.
General-purpose policy engine that separates the decision from whoever enforces it: you pass it data (for example a Terraform plan as JSON) and it evaluates rules written in Rego. It is used to stop a change before apply when it breaks a cost or security rule.
Open Policy Agent (OPA) is a lightweight, general-purpose policy engine. Its documentation describes the model like this: a service offloads a decision by executing a query, and OPA evaluates policies and data to produce a result. Policies are written in Rego, a high-level declarative language, and are loaded from the local filesystem or remotely through APIs.
The core idea is to decouple policy from the software that enforces it. Instead of burying rules such as "only these instance types" inside pipeline code, you describe them in files that are versioned, reviewed and tested on their own. That is what people usually call policy as code: the rule lives next to the code, not inside it.
OPA decides; whoever queries it enforces the decision (block a deploy, reject a request, flag a PR).
It is not tied to any domain: it reasons about arbitrary structured data, typically JSON or YAML.
It integrates as a sidecar, a host-level daemon or a library, and also ships as a command-line binary.
How it works: input, data, query and Rego
Rego works on documents. Whatever arrives with the query is read through the global variable input (for Terraform, the plan). Data loaded separately, such as an allowlist of instance types, lives under data. The rules you write produce "virtual" documents that are also queried under data, at the path set by the package directive.
For Terraform, the OPA docs describe three steps: save the plan with terraform plan -out, convert it with terraform show -json, and evaluate it. In the JSON plan representation, the key field is resource_changes: each element carries address, type and a change object with actions (for example create, update, delete), before and after.
opa eval takes the plan through -i/--input and policies or data through -d/--data; --fail-defined exits non-zero when the result is non-empty, which is exactly what you want with deny rules. opa exec evaluates a decision (--decision) against each input file. Conftest, a Rego-based tool for testing structured configuration, looks for deny, violation and warn rules (in the main namespace by default).
Since OPA v1.0 the in, every, if and contains keywords are part of the language by default, and if and contains are required when declaring rules. A current policy looks like this:
package terraform.guardrails
# Allowed instance types
allowed := {"t3.micro", "t3.small"}
deny contains msg if {
some rc in input.resource_changes
rc.type == "aws_instance"
"create" in rc.change.actions
not allowed[rc.change.after.instance_type]
msg := sprintf("%v: instance_type %v not on the allowlist", [rc.address, rc.change.after.instance_type])
}
deny contains msg if {
some rc in input.resource_changes
rc.type == "aws_instance"
"create" in rc.change.actions
not rc.change.after.tags.CostCenter
msg := sprintf("%v: missing CostCenter tag", [rc.address])
}
deny contains msg if {
deletes := [rc | some rc in input.resource_changes; "delete" in rc.change.actions]
count(deletes) > 5
msg := sprintf("the plan deletes %v resources (max 5)", [count(deletes)])
}
Where it matters for cloud cost and operations
The value is in stopping a change before apply, while nothing is billing yet. The OPA documentation itself lists three uses: giving each developer a first-pass review of their changes, auto-approving run-of-the-mill changes to reduce the peer-review burden, and enforcing organizational rules around infrastructure changes.
Cost: reject instance types not on an allowlist, or require cost-center tags so the bill can be split.
Security: block ingress rules open to 0.0.0.0/0 or public buckets by inspecting attributes in change.after.
Blast radius: cap how many resources a single plan creates or deletes; the official tutorial weights creations, deletions and modifications per resource type and only authorizes below a threshold.
Extra context: the input can combine the plan with the user running it (input.user, input.plan) to vary the threshold per person.
Control Cloud does not run OPA or Rego: its pre-deploy verification is its own set of checks on the account inventory (connection, network, subnet, internet egress). If you want the same idea applied to your plans, OPA is the piece that runs in your pipeline; see the docs and the AWS guide.
Limits and caveats
OPA only sees what the JSON plan contains. The official docs warn that some information is not available at plan time: computed attributes that are only determined at apply, dynamic blocks, and results of functions not yet evaluated. In the JSON, those values are flagged in after_unknown, not in after. Before writing a rule, confirm the data you need is actually in the plan.
There is no cost data: OPA does not know what an instance type costs unless you feed it a price table as data.
A plan that passes policy does not guarantee a green apply: quotas, capacity or permissions fail at the provider, not in Rego.
Attribute paths depend on the provider and resource type; a provider version bump can silently make a rule stop matching.
The plan JSON can contain sensitive values (before_sensitive/after_sensitive only flag which ones), so treat tfplan.json as a secret.
Policies need upkeep: allowlists, exceptions and thresholds age like any other code.
Best practices
Test policies the way you test code. In Rego, a test is a rule whose name starts with test_, ideally in a package suffixed with _test, and the with keyword swaps input and data for fixtures. opa test . -v runs every test; with Conftest the equivalent is conftest verify.
package terraform.guardrails_test
import data.terraform.guardrails
test_rechaza_tipo_no_permitido if {
plan := {"resource_changes": [{
"address": "aws_instance.web", "type": "aws_instance",
"change": {"actions": ["create"], "after": {"instance_type": "x1.32xlarge", "tags": {"CostCenter": "42"}}}
}]}
count(guardrails.deny) == 1 with input as plan
}
Use opa test --coverage and --threshold to fail CI when coverage drops, and --fail-on-empty so a misnamed test cannot pass silently.
Run opa check --strict before publishing, especially when migrating policies written before v1.0.
Keep real terraform show -json fixtures in the repo: hand-written tests tend to omit fields the plan actually carries.
Separate data from logic: allowlists and thresholds in JSON files loaded with -d, rules in .rego.
Write deny messages that include the resource address, so whoever reads the pipeline knows what to fix.
Frequently asked questions
Does OPA replace terraform plan?
No. OPA reads the plan Terraform already computed, converted to JSON with terraform show -json, and decides whether it meets your rules. Without a plan there is nothing to evaluate.
What is the difference between OPA and Conftest?
OPA is the general-purpose policy engine. Conftest is a tool for testing structured configuration files that uses Rego and follows fixed conventions, such as deny, violation and warn rules in the main namespace.
Why does my old policy fail to compile on OPA 1.0?
Since v1.0 the if and contains keywords are required when declaring rules. You can update the syntax or, while migrating, use compatibility mode with --v0-compatible.
Can OPA block a plan because of cost?
Only if you give it the data. The plan JSON carries no prices, so you have to load your own table as data or stick to indirect rules, such as an allowlist of instance types.