Open Policy Agent (OPA)

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.

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.

terraform plan -out tfplan.binary
terraform show -json tfplan.binary > tfplan.json
opa eval --fail-defined -i tfplan.json -d policy/ "data.terraform.guardrails.deny[x]"
opa exec --decision terraform/guardrails/deny --bundle policy/ tfplan.json
conftest test --policy policy/ --namespace terraform.guardrails tfplan.json

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.

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.

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
}

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.

Related terms: Terraform · Pre-flight check · Blast radius · IaC (Infrastructure as Code)

Related cost-saving policies: AWS EBS: delete unattached volumes

Ready to see it on your own infrastructure? Book a demo · Read the documentation