01Why Rego exists
Every system makes policy decisions: can this user delete this record? may this container run? is the agent allowed to call this tool? Usually that logic is scattered across services as if statements, written in different languages, reviewed by nobody and tested rarely.
Rego pulls those decisions out into one place. Policy becomes a versioned, reviewable, testable artifact, and every service asks the same engine the same kind of question.
Decision ≠ enforcement
The service enforces; OPA decides. Change policy without redeploying the app.
Say what, not how
Rules state conditions. The engine figures out the search over your JSON.
One language, many layers
APIs, Kubernetes, CI pipelines, Terraform plans, service mesh, AI agent tool calls.
02The mental model
OPA is a function. It takes input (the question, as JSON), consults data (facts it already knows) and policy (your Rego), and returns a decision (also JSON).
{
"user": {"name": "bob",
"role": "viewer"},
"method": "DELETE",
"path": ["reports","r2"]
}{
"allow": false
}Two global documents are always available:
| Name | What it holds | Example |
|---|---|---|
input | The request being decided, supplied per query | input.user.role |
data | Loaded facts (JSON/YAML) and every rule from every package | data.reports.r1.owner, data.httpapi.authz.allow |
03Anatomy of a policy
Here is a complete, realistic HTTP API authorization policy. Read the numbered notes alongside it.
policy.regopackage httpapi.authz # ①
default allow := false # ②
# Admins can do anything ③
allow if {
input.user.role == "admin"
}
# Analysts and viewers can read reports
allow if {
input.method == "GET" # ④
input.path[0] == "reports"
input.user.role in {"analyst", "viewer"}
}
# Owners can edit or delete their own report
allow if {
some id # ⑤
input.method in {"PUT", "DELETE"}
input.path = ["reports", id] # ⑥
data.reports[id].owner == input.user.name
}
- package namespaces the rules. This policy's decision lives at
data.httpapi.authz.allow. - default gives a value when no rule matches. Without it,
allowwould be undefined, notfalse(more on that in Gotchas). - Each
allow if { … }is one way to be allowed. Multiple definitions of the same rule are OR. - Lines inside a body are AND. Every one must hold.
some iddeclares a local variable whose value Rego will search for.=is unification: "make these two sides equal". It checks the path shape and bindsidto the second segment in one step.
04AND, OR, NOT — the whole logic system
Rego has no && or || operators. Boolean logic comes from structure.
Put conditions on separate lines in one body.
allow if {
input.method == "GET"
input.user.verified
}Define the same rule more than once.
allow if input.user.role == "admin" allow if input.user.role == "auditor"
not succeeds when the expression is false or undefined.
deny if not input.user.verified
Membership in arrays, sets and object values.
input.user.role in {"analyst", "viewer"}allow if input.user.role == "admin".05Watch the policy evaluate
This simulates OPA evaluating the policy from section 03. Change the request and see which lines pass, which fail, and where evaluation stops. A body stops at the first failing line, so later lines show as skipped.
input
data
Evaluation trace
Try this: the starting request is allowed because bob owns r2 (Rule 3), even though viewers can't normally delete. Switch the path to reports/r1, which alice owns, and watch Rule 3 fail on its last line. Then switch the role to admin.
06The four kinds of rules
Almost every policy is built from these four shapes.
1 · Complete rules — one value
Produce a single value. Booleans are the common case, but any JSON works.
default allow := false allow if input.user.role == "admin" max_upload_mb := 50 # a constant tier := "gold" if input.user.spend > 10000
2 · Partial set rules — collect many values
contains builds a set. Every match adds an element. This is the classic way to gather all violations instead of stopping at the first.
deny contains msg if {
not input.user.verified
msg := "user is not verified"
}
deny contains msg if {
input.amount > 1000
msg := sprintf("amount %v exceeds limit", [input.amount])
}
# Result could be: {"amount 5000 exceeds limit", "user is not verified"}
3 · Partial object rules — build a map
role_of[name] := role if {
some u in data.users
name := u.name
role := u.role
}
# {"alice": "analyst", "bob": "viewer", ...}
4 · Functions — reusable logic
is_owner(user, id) if data.reports[id].owner == user
allow if {
input.method == "DELETE"
is_owner(input.user.name, input.path[1])
}
contains) and summarize it.07Iteration and collections
You never write a loop. You state "there is some element such that…" or "every element satisfies…", and Rego searches.
Existential: some … in
True if at least one element matches.
has_admin if {
some u in data.users
u.role == "admin"
}Universal: every
True if all elements match (and trivially true for empty input).
all_pinned if {
every c in input.containers {
not endswith(c.image, ":latest")
}
}Comprehensions — build a collection inline
admins := {u.name | some u in data.users; u.role == "admin"} # set
names := [u.name | some u in data.users] # array
roles_by := {u.name: u.role | some u in data.users} # object
n_admins := count(admins)
Key/value iteration
some key, value in input.labels # objects some i, item in input.items # arrays, with index
08Worked examples
Three policies you could actually ship. Each shows the input it expects and what it returns.
Reject pods whose containers have no memory limit or use a floating :latest tag. Written in the style used by Conftest; Gatekeeper wraps the same logic in a violation rule inside a ConstraintTemplate.
k8s/pods.regopackage k8s.pods
deny contains msg if {
input.kind == "Pod"
some c in input.spec.containers
not c.resources.limits.memory
msg := sprintf("container %q has no memory limit", [c.name])
}
deny contains msg if {
input.kind == "Pod"
some c in input.spec.containers
endswith(c.image, ":latest")
msg := sprintf("container %q uses the :latest tag", [c.name])
}
deny contains msg if {
input.kind == "Pod"
some c in input.spec.containers
c.securityContext.privileged == true
msg := sprintf("container %q runs privileged", [c.name])
}
input (abridged){
"kind": "Pod",
"spec": {"containers": [
{"name": "web", "image": "nginx:latest",
"resources": {"limits": {"memory": "256Mi"}}},
{"name": "sidecar", "image": "envoy:1.30"}
]}
}
data.k8s.pods.deny[
"container \"sidecar\" has no memory limit",
"container \"web\" uses the :latest tag"
]
Put a policy check between an AI agent and its tools. The agent runtime sends each proposed tool call to OPA before executing it. The policy fails closed: an unknown agent or tool is denied by construction.
agent/tools.regopackage agent.tools
high_risk := {"send_email", "transfer_funds", "delete_record"}
default allow := false
allow if count(deny) == 0
deny contains "tool is not on this agent's allowlist" if {
not input.tool.name in data.agents[input.agent.id].allowed_tools
}
deny contains "high-risk tool needs human approval" if {
input.tool.name in high_risk
not input.approval.granted
}
deny contains msg if {
input.tool.name == "send_email"
some r in input.tool.args.to
not endswith(r, "@contoso.com")
msg := sprintf("external recipient %s is blocked", [r])
}
deny contains "transfer exceeds per-call limit" if {
input.tool.name == "transfer_funds"
input.tool.args.amount > data.limits.max_transfer
}
# Return everything the runtime needs in one query
decision := {"allow": allow, "reasons": deny}
input — proposed tool call{
"agent": {"id": "support-bot"},
"tool": {
"name": "send_email",
"args": {"to": ["pat@contoso.com",
"x@gmail.com"]}
},
"approval": {"granted": false}
}
data.agent.tools.decision{
"allow": false,
"reasons": [
"external recipient x@gmail.com is blocked",
"high-risk tool needs human approval"
]
}
reasons set doubles as feedback the agent can read to re-plan, or as the prompt shown to a human approver.Run against terraform show -json plan.out in CI to stop risky changes before apply.
terraform/plan.regopackage terraform.plan
deny contains msg if {
some rc in input.resource_changes
rc.type == "aws_s3_bucket_public_access_block"
rc.change.after.block_public_acls == false
msg := sprintf("%s allows public ACLs", [rc.address])
}
deny contains msg if {
some rc in input.resource_changes
"delete" in rc.change.actions
rc.type in {"aws_db_instance", "aws_rds_cluster"}
msg := sprintf("plan deletes database %s", [rc.address])
}
warn contains msg if {
some rc in input.resource_changes
rc.change.after.tags.owner == null
msg := sprintf("%s has no owner tag", [rc.address])
}
Run it with conftest test plan.json -p terraform/. Conftest fails the build on deny and prints warn.
09Gotchas that bite everyone once
Undefined is not false
If no rule body succeeds and there's no default, the rule has no value. A query for it returns an empty result, and your service must decide what that means.
without defaultallow if input.user.role == "admin"
# guest asks → result: {} (undefined)
with defaultdefault allow := false
allow if input.user.role == "admin"
# guest asks → result: {"result": false}
A reference to a missing field is also undefined, which quietly makes that line fail. input.user.rol == "admin" (typo) never errors — it just never matches. Linting and tests catch this.
Three kinds of "equals"
| Operator | Meaning | Use it for |
|---|---|---|
:= | Assign a local variable (error if already bound) | msg := "denied" |
== | Compare two known values | input.method == "GET" |
= | Unify: bind unknowns so both sides match | input.path = ["reports", id] |
Rule of thumb: use := and == by default; reach for = only when you want pattern matching.
More traps
Order doesn't matter
Rego reorders body expressions for safety. Don't rely on line order for side effects — there are none.
Conflicting complete rules
Two bodies yielding different values for one complete rule = error. Use contains sets or else chains.
not needs bound variables
not data.users[x].banned with unbound x is "unsafe". Bind x first with some.
Old v0 syntax online
Many blog posts predate OPA 1.0 and omit if / contains. Modern Rego requires both; opa fmt can upgrade old files.
10Testing and running
Tests are just rules whose names start with test_. The with keyword swaps in fake input or data for that one expression.
policy_test.regopackage httpapi.authz_test
import data.httpapi.authz
test_admin_can_delete if {
authz.allow with input as {
"user": {"name": "zoe", "role": "admin"},
"method": "DELETE", "path": ["reports", "r1"]
}
}
test_owner_can_edit_own_report if {
authz.allow with input as {
"user": {"name": "alice", "role": "viewer"},
"method": "PUT", "path": ["reports", "r1"]
} with data.reports as {"r1": {"owner": "alice"}}
}
test_viewer_cannot_delete_others if {
not authz.allow with input as {
"user": {"name": "bob", "role": "viewer"},
"method": "DELETE", "path": ["reports", "r1"]
} with data.reports as {"r1": {"owner": "alice"}}
}
The commands you'll use daily
shell# Evaluate one query against files
opa eval -d policy.rego -d data.json -i input.json "data.httpapi.authz.allow"
# Run all tests (with coverage)
opa test . -v
opa test . --coverage
# Format (and upgrade style)
opa fmt -w .
# Run as a server, then ask it over HTTP
opa run --server policy.rego data.json
curl -X POST localhost:8181/v1/data/httpapi/authz/allow \
-d '{"input": {"user": {"role": "admin"}, "method": "GET", "path": ["reports"]}}'
# → {"result": true}
opa test.11Where Rego runs
Rego runs in self-hosted OPA and its integrations, and in managed agent-governance services.
OPA sidecar / daemon
Apps call the REST API locally. Policies and data are pushed via bundles.
Gatekeeper
Admission control with Rego inside ConstraintTemplates; audits existing resources too.
Conftest
Tests any structured file: Kubernetes YAML, Terraform plans, Dockerfiles, CI configs.
Envoy ext_authz
OPA-Envoy plugin authorizes requests at the proxy, before they hit your code.
Go library & Wasm
Embed the engine in Go, or compile policies to WebAssembly for other runtimes.
Tool-call gating
Check every proposed tool call against policy before execution, as in example 08.
Managed option: Microsoft Foundry Agent Controls Public preview
Microsoft recently released Agent Controls, a managed service in Microsoft Foundry for defining and evaluating runtime policies on agent behavior. Its decision logic is written in Rego, so everything on this page carries over. It is built on the open-source Agent Control Specification (ACS) and Agent Hooks, and it governs what an agent does (tool calls, transactions, access to sensitive data, generated content), not only what it says.
| Agent Controls concept | What it is | Rego equivalent on this page |
|---|---|---|
| Manifest + Rego modules | A JSON manifest binds an intervention point and a target to a Rego query. Rego holds the decision logic. | The policy file, plus the query you pass to opa eval |
| Intervention point | When to check: agent_startup, input, pre_model_call, post_model_call, pre_tool_call, post_tool_call, output, agent_shutdown | Where your runtime calls OPA. Example 08's guardrail is a pre_tool_call check. |
| Snapshot / target | The current agent event, and the part of it being checked (for example tool_call.args) | input |
| Annotator | An Azure AI Content Safety classifier or an LLM judge that runs before Rego and adds an annotation the policy can read | Extra facts in input or data |
| Verdict | allow, deny or transform, optionally with warnings or an approval request | A decision object built from allow and deny contains reasons |
| Evaluation receipt | A record of the policies and versions evaluated, the intervention point and an evaluation ID | OPA decision logs |
Microsoft's walkthrough uses a refund guard: the manifest binds pre_tool_call to the Rego query data.refund_guard.verdict and evaluates tool_call.args. A $150 refund over the $100 limit gets deny, and a $75 refund gets allow. A policy in that shape could look like this (an illustration, not Microsoft's source):
refund_guard.rego (illustrative)package refund_guard
max_refund := 100
verdict := "deny" if input.amount > max_refund
else := "allow"
Preview details, verdict formats and APIs may change. During preview, billing covers only the classifier and LLM usage that policy evaluation triggers. Check the official docs before you build on it.
For the full picture of the service, with intervention points, manifests, verdicts and a refund-guard simulator, read the Agent Controls primer.
12Cheat sheet
Skeleton
package my.policy
import data.other.pkg
default allow := false
allow if { … }Logic
a; b on separate lines → AND same rule twice → OR not expr → NOT / undefined x in collection → membership
Rule shapes
r := v if { … } complete
s contains v if { … } set
o[k] := v if { … } object
f(x) := y if { … } functionIteration
some x in xs
some k, v in obj
every x in xs { cond }
{x | some x in xs; cond}Equality
:= assign local == compare = unify / pattern match
Useful built-ins
count sum max min sort startswith endswith contains sprintf concat split lower regex.match time.now_ns json.unmarshal io.jwt.decode
Else chain
level := "high" if input.score > 80 else := "med" if input.score > 50 else := "low"
Testing
test_name if {
rule with input as {…}
with data.x as {…}
}
opa test . -v13Next steps
- Play first. Paste the section 03 policy into the official Rego Playground (play.openpolicyagent.org) and edit the input until you can predict every result.
- Install OPA locally and run
opa evalandopa testagainst the examples on this page. - Pick one real decision in a system you own — an admin endpoint, a CI gate, an agent tool — and move just that one into Rego with tests.
- Add Regal and
opa test --coverageto CI so policy changes get the same review discipline as code. - Return decisions with reasons (the
deny contains msgpattern). It makes failures debuggable and audit logs useful.