OPA · Cheat sheet

OPA & Rego cheat sheet

OPA and Rego cheat sheet: CLI, rules, testing, conftest, bundles, decision API, and Gatekeeper examples.

47 commands·6 sections·Updated ·By SecOpsLog

Rows marked Destructive State operation Caution Exposes secrets can remove data, change authoritative state, affect a running system, or print secrets. Read the note before running them against anything that matters.

opa CLI

Beginner
opa version
Print the OPA version.
opa run
Start an interactive Rego REPL.
opa run -s
Run OPA as a server on localhost:8181 (1.0+); use --addr 0.0.0.0:8181 to expose.
opa eval -d policy.rego -i input.json "data.example.allow"
Evaluate a query against policy + input.Example output
{"result":[{"expressions":[{"value":true,...}]}]}
opa eval -f pretty -d . "data.example.deny"
Pretty output; load a whole directory.
opa fmt -w policy.rego
Auto-format Rego in place.
opa fmt --write --v0-v1 .
Rewrite pre-1.0 Rego so both OPA 0.x and 1.x parse it.
opa check .
Type-check every policy in a directory.
opa test . -v
Run *_test.rego unit tests.Example output
data.example.test_allow: PASS (312µs)
PASS: 5/5
opa test --coverage -f json .
Report per-line policy coverage.
opa eval --partial -d policy.rego "data.example.allow"
Partial evaluation: input stays unknown and the result is the residual policy (data filtering).
opa eval --explain=fails -d . "data.example.allow"
Show which expressions failed: the quickest answer to why a rule is false.
opa bench -d policy.rego -i input.json "data.example.allow"
Benchmark a query (ns/op, allocations) before it sits on a hot request path.

Rego basics

Beginner
package example
Every file begins with a package (its namespace under data).
import rego.v1
Only needed for OPA 0.x; v1 syntax (if/contains) is the default since OPA 1.0.
default allow := false
A safe default so undefined never means allowed.
allow if { input.method == "GET" }
A rule — true when its body holds.
deny contains msg if { ... }
Collect violation messages into a set.
test_get_allowed if { allow with input as {"method": "GET"} }
Unit test: override input (or data) with the with keyword; opa test runs every test_ rule.
print("method:", input.method)
Debug output, shown by opa test -v and on stderr during eval.
input.user.role
The request document you pass in with -i.
data.example.allow
Reference a computed rule from elsewhere.

Rego language

Intermediate
some i; input.items[i].public
Introduce a variable and iterate.
every x in input.ports { x < 1024 }
Universal quantifier — all must hold.
names := [u.name | u := input.users[_]]
Comprehension — build a list.
count(input.spec.containers) <= 3
count works on arrays, sets, objects and strings; sum and max take only arrays or sets.
startswith(input.image, "reg.io/")
String helpers: startswith/endswith/contains.
regex.match("^v[0-9]+$", input.tag)
Regex matching.
object.get(input, ["a","b"], "def")
Safe nested lookup with a default.

conftest (config files)

Intermediate
conftest test deployment.yaml
Test a YAML/JSON/HCL file against policy/.Example output
FAIL - deployment.yaml - main - container must set runAsNonRoot
1 test, 0 passed, 0 warnings, 1 failure, 0 exceptions
conftest test -p policy/ k8s/*.yaml
Point at a specific policy directory.
conftest verify
Run the policy’s own unit tests.
conftest test --output json app.yaml
JSON results for CI parsing.
conftest test --namespace main file.yaml
Only evaluate rules in one package.
conftest push / pull ghcr.io/org/policy
Ship/fetch policy bundles as OCI artifacts.

Bundles & decision API

Advanced
opa build -b policy/ -o bundle.tar.gz
Compile policies + data into a bundle.
opa run -s -b bundle.tar.gz
Serve a bundle over the REST API.
opa inspect bundle.tar.gz
Show a bundle's manifest, Rego version and namespaces before you ship it.
opa run -s --set decision_logs.console=true policy/Exposes secrets
Log every decision (input, result, decision_id) to stdout.Exposes secrets: Decision logs record the full input; mask sensitive fields before shipping them.
opa run -s --authentication=token --authorization=basic policy/ authz.rego
Require a bearer token and enforce your data.system.authz policy on every API call.
curl localhost:8181/v1/data/example/allow -d @input.json
Ask the server for a decision; the body must be {"input": ...}.Example output
{"result":true}
opa eval --profile -d . "data"
Profile which rules cost the most.

Gatekeeper (K8s admission)

Advanced
kubectl apply -f constrainttemplate.yaml
Register a reusable Rego policy as a CRD.
kubectl apply -f constraint.yaml
Instantiate the template with parameters.
kubectl get constraints
List active constraints and violation counts.
kubectl get constrainttemplates
List installed policy templates.
gator test -f policy/ -f resources/
Test Gatekeeper policies locally before applying.

Primary references

Found a technical issue on this page? Report it with the tool version you used and the behavior you saw. How resources are maintained.

Go deeper
Hands-on courses for OPA