Opscraft
Open Policy Agent · Lesson 2 of 9 · 6 min read

The Rego language

Mental model

Rego is a declarative query language inspired by Datalog. You don't write steps; you write rules that are true when conditions hold. A rule body is a set of expressions that must all be true (logical AND). Multiple definitions of the same rule are ORed. If any expression is false or undefined, the rule doesn't apply.

OPA 1.0 (released December 2024) made the modern syntax the default: rule bodies use the if keyword and multi-value rules use contains. Older policies (and many Gatekeeper library templates) use the earlier syntax without these keywords — you'll read both.

A first policy

Enlarge diagramdeny contains msg if {head: add msg to the deny set if…container := input.…containers[_]for some containernot startswith(container.image, "1234….ecr…")AND its image is not from our ECRmsg := sprintf("image %v not allowed", …)AND build the message}
Figure 1. How to read a Rego rule: the head is true when every line in the body is true. Lines are joined by AND.
Swipe sideways to see all of it, or tap to open it full screen.
package kubernetes.admission

import rego.v1          # opt into v1 syntax on older OPA versions; implicit in OPA 1.0+

# Deny containers using the :latest tag or no tag at all
deny contains msg if {
    input.request.kind.kind == "Pod"
    some c in input.request.object.spec.containers
    not has_pinned_tag(c.image)
    msg := sprintf("container %q must use a pinned image tag, got %q", [c.name, c.image])
}

has_pinned_tag(image) if {
    contains(image, ":")
    not endswith(image, ":latest")
}

# Require CPU and memory limits
deny contains msg if {
    some c in input.request.object.spec.containers
    not c.resources.limits.memory
    msg := sprintf("container %q has no memory limit", [c.name])
}

Key elements:

  • package — namespaces the rules; the decision lives at data.kubernetes.admission.deny.
  • deny contains msg if { ... } — a partial set rule: builds a set of messages; every way the body can succeed adds an element. An empty set means no violations.
  • some c in ... — iteration: the body is evaluated for each container.
  • not — negation: true when the expression is false or undefined.
  • := — local assignment; == — comparison; = — unification.
  • Helper rules/functions like has_pinned_tag(image) keep policies readable.

Rule types

# Boolean rule with a default
default allow := false
allow if {
    input.user.role == "admin"
}
allow if {                         # second definition = OR
    input.method == "GET"
    input.path[0] == "public"
}

# Complete value rule
max_replicas := 10 if input.env == "prod"
max_replicas := 3  if input.env != "prod"

# Partial object rule
owners[ns] := team if {
    some ns_obj in data.kubernetes.namespaces
    ns := ns_obj.metadata.name
    team := ns_obj.metadata.labels.owner
}

default allow := false is the deny-by-default pattern: unless some rule makes allow true, the answer is false (not undefined).

Undefined vs false

If a referenced field doesn't exist (input.request.object.spec.securityContext.runAsNonRoot when there's no securityContext), the expression is undefined, and the rule body simply fails — it doesn't error. That's why not c.resources.limits.memory works for "missing" checks. It's also a classic bug source: a typo in a path makes a deny rule silently never fire. Unit tests catch this.

Enlarge diagramPitfallSafer…runAsNonRoot == falseField missing → undefinedRule never fires: object allowednot …runAsNonRoot == trueMissing counts as a violationUnit-test the empty case
Figure 2. Undefined is not false. A missing field makes a body fail silently, which can let objects through. Check for absence on purpose.
Swipe sideways to see all of it, or tap to open it full screen.

Iteration, quantifiers and comprehensions

# any container privileged?
some c in input.spec.containers
c.securityContext.privileged == true

# every container from our registry?
every c in input.spec.containers {
    startswith(c.image, "123456789012.dkr.ecr.ap-south-1.amazonaws.com/")
}

# comprehensions
images := [c.image | some c in input.spec.containers]          # array
names  := {c.name | some c in input.spec.containers}           # set
ports  := {c.name: c.ports | some c in input.spec.containers}  # object

Useful built-ins

String: startswith, endswith, contains, sprintf, split, lower, regex.match, glob.match. Collections: count, object.get(obj, key, default), array.concat, set operations (|, &, -). Others: time.now_ns, net.cidr_contains, json/yaml encoding, semver.compare, http.send (for external data — use sparingly in admission paths).

Testing Rego

package kubernetes.admission_test

import rego.v1
import data.kubernetes.admission

test_latest_tag_denied if {
    some msg in admission.deny with input as {"request": {"kind": {"kind": "Pod"},
        "object": {"spec": {"containers": [{"name": "app", "image": "nginx:latest",
            "resources": {"limits": {"memory": "128Mi"}}}]}}}}
    contains(msg, "pinned image tag")
}

test_pinned_tag_allowed if {
    count(admission.deny) == 0 with input as {"request": {"kind": {"kind": "Pod"},
        "object": {"spec": {"containers": [{"name": "app", "image": "nginx:1.27.2",
            "resources": {"limits": {"memory": "128Mi"}}}]}}}}
}
opa test policies/ -v                   # run tests
opa test policies/ --coverage           # coverage report
opa eval -d policies/ -i pod.json "data.kubernetes.admission.deny"   # evaluate ad hoc
opa fmt -w policies/                    # format
opa check --strict policies/            # static checks

The Rego Playground (play.openpolicyagent.org) is ideal for experimenting. When a policy "doesn't trigger", evaluate it against a real sample input with opa eval and inspect each expression.

Enlarge diagramtest_ allowedimage from our ECR → nodenytest_ denieddocker.io image → 1 denyopa test -vin CI, with --coverage
Figure 3. Testing Rego: write a test per allowed and denied example, run opa test in CI, and track coverage.
Swipe sideways to see all of it, or tap to open it full screen.