Vikas Goyal / Agentic AI / Rego primer
Primer · Policy as code

Rego, explained by example

Rego is the declarative language behind Open Policy Agent (OPA). You describe what must be true for a decision, hand it some JSON, and get a decision back. This page builds the mental model, lets you watch a policy evaluate line by line, then walks through real policies for APIs, Kubernetes and AI agents, including Microsoft Foundry Agent Controls, which uses Rego for agent runtime policy.

~20 min read Rego v1 syntax (OPA 1.x) Interactive evaluator Cheat sheet at the end For AI agents: Markdown version

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.

Decouple

Decision ≠ enforcement

The service enforces; OPA decides. Change policy without redeploying the app.

Declare

Say what, not how

Rules state conditions. The engine figures out the search over your JSON.

Unify

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).

Key ideaRego is not a scripting language. There are no loops you write, no variables you mutate, no statements executed in order "for effect". You write assertions, and a rule's value is defined only if all of its assertions can be made true.

Two global documents are always available:

NameWhat it holdsExample
inputThe request being decided, supplied per queryinput.user.role
dataLoaded facts (JSON/YAML) and every rule from every packagedata.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
}
  1. package namespaces the rules. This policy's decision lives at data.httpapi.authz.allow.
  2. default gives a value when no rule matches. Without it, allow would be undefined, not false (more on that in Gotchas).
  3. Each allow if { … } is one way to be allowed. Multiple definitions of the same rule are OR.
  4. Lines inside a body are AND. Every one must hold.
  5. some id declares a local variable whose value Rego will search for.
  6. = is unification: "make these two sides equal". It checks the path shape and binds id to the second segment in one step.

04AND, OR, NOT — the whole logic system

Rego has no && or || operators. Boolean logic comes from structure.

AND

Put conditions on separate lines in one body.

allow if {
    input.method == "GET"
    input.user.verified
}
OR

Define the same rule more than once.

allow if input.user.role == "admin"
allow if input.user.role == "auditor"
NOT

not succeeds when the expression is false or undefined.

deny if not input.user.verified
IN

Membership in arrays, sets and object values.

input.user.role in {"analyst", "viewer"}
TipFor a simple one-condition rule you can drop the braces: 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
default allow := false

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])
}
Watch outA complete rule that produces two different values for the same input is a runtime conflict error. If several conditions can match at once, use a partial set (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"
]

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"

OperatorMeaningUse it for
:=Assign a local variable (error if already bound)msg := "denied"
==Compare two known valuesinput.method == "GET"
=Unify: bind unknowns so both sides matchinput.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}
Lint itRegal is the community linter for Rego. It flags unused variables, risky patterns and style issues, and runs well in CI next to opa test.

11Where Rego runs

Rego runs in self-hosted OPA and its integrations, and in managed agent-governance services.

Service

OPA sidecar / daemon

Apps call the REST API locally. Policies and data are pushed via bundles.

Kubernetes

Gatekeeper

Admission control with Rego inside ConstraintTemplates; audits existing resources too.

CI

Conftest

Tests any structured file: Kubernetes YAML, Terraform plans, Dockerfiles, CI configs.

Mesh

Envoy ext_authz

OPA-Envoy plugin authorizes requests at the proxy, before they hit your code.

Embedded

Go library & Wasm

Embed the engine in Go, or compile policies to WebAssembly for other runtimes.

Agents

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 conceptWhat it isRego equivalent on this page
Manifest + Rego modulesA 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 pointWhen to check: agent_startup, input, pre_model_call, post_model_call, pre_tool_call, post_tool_call, output, agent_shutdownWhere your runtime calls OPA. Example 08's guardrail is a pre_tool_call check.
Snapshot / targetThe current agent event, and the part of it being checked (for example tool_call.args)input
AnnotatorAn Azure AI Content Safety classifier or an LLM judge that runs before Rego and adds an annotation the policy can readExtra facts in input or data
Verdictallow, deny or transform, optionally with warnings or an approval requestA decision object built from allow and deny contains reasons
Evaluation receiptA record of the policies and versions evaluated, the intervention point and an evaluation IDOPA 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"
The host still enforcesLike OPA, Agent Controls only decides. It doesn't run your agent, execute tools or sandbox the process, and it can't stop a call that bypasses your interception code. Your agent host must check the verdict and block the tool call itself. Keep authorization and authoritative business data in your trusted systems.

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 { … }       function

Iteration

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 . -v

13Next steps

  1. 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.
  2. Install OPA locally and run opa eval and opa test against the examples on this page.
  3. 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.
  4. Add Regal and opa test --coverage to CI so policy changes get the same review discipline as code.
  5. Return decisions with reasons (the deny contains msg pattern). It makes failures debuggable and audit logs useful.