Rego Language Basics
What you'll learn: How to write rules and queries in Rego, the declarative policy language that powers Open Policy Agent.
What is Rego?
Rego (pronounced "ray-go") is a declarative query language specifically designed for writing policies. Unlike procedural languages where you tell the computer how to do something, Rego lets you define what should be true. Think of it like writing rules for a game: you state the conditions that must be met, and OPA figures out whether those conditions are satisfied.
Core Rego Concepts
Rules
A rule is a logical statement that produces a value. The simplest form assigns a value when conditions are met:
allow = true {
input.user == "admin"
}
This reads: "allow is true when the input user equals admin."
Queries
You can query your rules to evaluate them against specific data. Rules without conditions always evaluate:
default allow = false
allow {
input.role == "developer"
input.environment != "production"
}
Here, allow defaults to false but becomes true when both conditions match.
Basic Logic
Rego uses logical AND (multiple statements in one rule block) implicitly. Each line must be true for the rule to succeed:
valid_request {
input.method == "GET"
input.path[0] == "api"
count(input.path) > 1
}
All three conditions must hold for valid_request to be true.
Reading Rego
Think of each rule as asking: "Under what circumstances is this true?" You're defining the conditions, not the steps. OPA evaluates your rules against real data to make policy decisions.
Key Takeaway: Rego lets you write infrastructure and security policies as declarative rules that define "what should be true" rather than procedural steps, making policies readable, testable, and maintainable.