Time: ~90 minutes · Difficulty: Beginner to intermediate · You need: a terminal and the opa binary, and for step 5, Conftest and Terraform with a Terraform configuration of your own to plan
How this page was checked: every policy, test and command on this page, including the exercise answers, was run with OPA 1.22.2, Conftest 0.71.1 and Regal 0.43.0 on an Apple silicon Mac, and the outputs described are what they printed. The brew install lines are the exception: they were not run, because they install software for the whole machine. The Terraform plan in step 5 was made with Terraform 1.15.7 and AWS provider 5.100.0 using dummy credentials, so its JSON is real but no AWS account was involved and nothing was applied.
Slides: download the PDF or make your own editable copy (copying needs a Google account). The slides are licensed CC BY-NC 4.0.
What OPA is
Security teams have rules such as "every storage bucket must be encrypted" or "no firewall rule may open SSH to the whole internet", and they want each proposed change checked against those rules automatically, before the change goes live. Open Policy Agent (OPA) does that checking. It is a general-purpose policy engine: a policy is a set of rules like those, and the engine is the program that applies them. You write the rules in OPA's own language, Rego, and most of this page teaches it.
"General-purpose" is vague on purpose, and the vagueness is the point: OPA does not know what Kubernetes is, what Terraform is, or what an S3 bucket is. It knows one thing. You hand it a JSON document (JSON is the plain-text format of named values, nested objects and lists that most cloud tools use to describe things), it evaluates rules against that document, and it hands you back a decision, also JSON. On this page the decision is a set of messages, one for each violation it finds, such as "bucket prod-invoices is not encrypted".
Everything else is plumbing built around that core: tools that take a document from somewhere and feed it to OPA. Gatekeeper is plumbing that feeds Kubernetes admission requests into OPA. (When someone asks a Kubernetes cluster to create or change something, the cluster can send the request to a checker such as Gatekeeper before carrying it out, and that request is an admission request.) Conftest is plumbing that feeds a Terraform plan, Terraform's list of the changes it is about to make to your cloud, into OPA. Envoy's external authorization filter is plumbing that feeds an HTTP request into OPA, so that Envoy, a proxy that sits in front of web services, can ask OPA whether to let the request through. The engine underneath is identical in all three, and so is the language.
That is the practical reason to learn Rego rather than any single tool's rule format. A Sentinel policy works in HCP Terraform, HashiCorp's hosted service for running Terraform. A Kyverno policy works in Kubernetes. Rego is the one policy language that a cloud security engineer runs into at the infrastructure layer (cloud resources, as in a Terraform plan), the orchestration layer (Kubernetes) and the application layer (web requests, as with Envoy), and it is a CNCF graduated project, so it is not going anywhere. The CNCF (Cloud Native Computing Foundation) is the foundation that hosts Kubernetes, and graduated is the highest of its project maturity levels.
Check your OPA version before you read any other tutorial. OPA 1.0 shipped on 20 December 2024 and changed the language's surface syntax: if before a rule body and contains for multi-value rules went from optional to mandatory. Most Rego on the internet predates that. Everything on this page is written for 1.x.
On this page
How to use this guide
This guide is marked beginner to intermediate. It assumes you can type commands into a terminal and read a short JSON document, and it teaches Rego from the start, so you need no policy language beforehand. Step 5 also uses Terraform, the tool that builds cloud resources from configuration files and can show the changes it plans to make before it makes them. The site's Terraform page explains it, using real configuration. That step needs Terraform installed and a Terraform configuration of your own to plan, which this page does not supply.
Read the page in order. The next section explains the one idea the rest depends on, with two short policies that are there to read. In the walk-through, step 1 installs OPA, steps 2 and 3 write a small policy about storage buckets and run it against a JSON file, step 4 extends it to a list of buckets, step 5 points a policy at a real Terraform plan with Conftest, and steps 6 and 7 test and tidy the policy. The exercises build on the files you made, with each answer hidden until you open Show the answer. If you have no Terraform configuration to hand, save step 5's policy/s3.rego anyway and carry on: steps 6 and 7 test and check that file without reading a plan, though exercises 1 and 2 need one.
Each code block has a label at the top and a copy button. A REGO block with a file name just above it, such as bucket.rego, is a policy file, and a block labelled JSON is an input document: save each under that name in the folder you run your commands from. The other REGO blocks are rules to read, or to put into the file the step names. From step 5 on, the policies live in a folder called policy inside it. A block labelled BASH holds commands to paste into your terminal, and the sentence before it says what they do. Text after a # in a REGO block is a comment explaining the line. This page has no separate output blocks: the sentence after most commands says what it should print.
What you see should match what the page describes. Every policy, test and command here, the exercise answers included, was run with OPA 1.22.2, Conftest 0.71.1 and Regal 0.43.0, and the page reports what they printed. Step 5 is the exception, because what Conftest reports depends on the Terraform configuration you plan: expect your own resource names, and no findings at all if your plan has no aws_s3_bucket_public_access_block resource.
If a result differs from the page, check three things. First, the OPA version: the page needs 1.x, and on 0.x every policy fails to parse. Second, the folder: every command names its files without saying which folder they are in, so run it from the folder that holds them. Third, the input: steps 2 and 3 have you edit bucket.json by hand, so make sure it holds what the step says. In step 5, also remember that Conftest by default reads only policies in package main.
Rules are questions about one JSON document
Picture a policy whose whole job is to require encryption on storage buckets. Hand it a bucket with no encryption setting at all, and it reports nothing: no error, no message, a pass. Step 3 makes exactly that happen. To see why, and to write rules that do not fall into it, you need one idea about how Rego works.
Rego is a query language rather than an imperative language wearing unfamiliar syntax, and the thing you are querying is a single JSON tree. An imperative language, such as Python or a shell script, runs a list of instructions in order. A query language describes what you are looking for and leaves the engine to find every match. Everything OPA knows lives at one of two roots:
inputis the document being decided about right now: the admission request, the Terraform plan, the HTTP request.datais everything else OPA has loaded: your policies, and any reference data you gave it (an allowlist of approved images, a mapping of teams to accounts).
A rule is a claim about that tree. opa eval asks whether the claim holds and what value it produces. Once you read rules as queries rather than as functions, the two things that confuse everybody stop being confusing.
Undefined is not false
In most languages a boolean expression is true or false. In Rego there is a third outcome, and it is the common one: undefined. A rule whose body cannot be satisfied does not return false. It returns nothing at all.
package example
# This rule is defined only when input.encrypted is exactly false.
unencrypted if { # `if` is mandatory in Rego v1
input.encrypted == false
}Feed that {"encrypted": true} and unencrypted is undefined. Feed it {} and it is also undefined, because input.encrypted does not exist and a reference to a missing key is itself undefined, which makes the whole body fail. Those two cases look identical from outside and they mean completely different things: one is an encrypted bucket, the other is a document you forgot to check. This is the largest source of policies that pass when they should fail. Step 3 shows it on a real input and fixes it.
Deny sets, not if-then-else
Idiomatic Rego does not return "allow" or "deny" from one big branch. It accumulates violations into a set, and each rule contributes independently. An empty set means nothing objected.
package example
# `contains` marks this as a multi-value (set) rule. Every matching
# input adds one more message to the set `deny`.
deny contains msg if {
input.encrypted == false
msg := "storage is not encrypted"
}
deny contains msg if {
input.public == true
msg := "storage is publicly readable"
}Both rules are named deny, and that is not a mistake. A bucket that is unencrypted and public produces a set with two messages. Because of this, policy-as-code tooling reports every violation at once instead of stopping at the first, and adding a new check never means editing an existing rule. Step 2 writes your first deny set, and step 4 has two rules add to the same one.
Walk-through
1. Install OPA and confirm you are on 1.x
On macOS, install OPA with Homebrew. On Linux, grab the static binary from the GitHub releases page.
brew install opa opa version
Confirm that opa version reports Version: 1.x: the syntax below needs it. If a package manager hands you 0.x, download the binary directly from the releases page instead. On 0.x every example here fails to parse, and the error message points at the if keyword rather than saying "your OPA is old", which is a confusing first hour.
2. Your first policy, evaluated from the command line
bucket.rego:
package storage # the package path becomes data.storage
deny contains msg if {
input.encryption.enabled == false
msg := sprintf("bucket %v is not encrypted", [input.name])
}bucket.json:
{ "name": "prod-invoices", "encryption": { "enabled": false }, "public": true }Evaluate the policy against the input. -d loads a policy file (or directory), -i loads the input document, and the final argument is the query: a path into the data tree.
opa eval -d bucket.rego -i bucket.json 'data.storage.deny'
Add --format pretty to print just the value instead of the full result envelope:
opa eval --format pretty -d bucket.rego -i bucket.json 'data.storage.deny'
You should get back a set containing one message. Now flip enabled to true in the input and run it again: the pretty output is [], an empty set. That empty set is your "allowed" signal.
3. Watch undefined bite you
Delete the whole encryption object from bucket.json so it reads {"name": "prod-invoices", "public": true}, then run the same command.
opa eval --format pretty -d bucket.rego -i bucket.json 'data.storage.deny'
It prints [], an empty deny set. The policy says this bucket is fine.
A bucket with no encryption configuration at all just passed a policy whose entire job is to require encryption. input.encryption.enabled is undefined, the body fails, no message is added. The fix is to stop asking "is it false" and start asking "is it not true":
deny contains msg if {
not input.encryption.enabled == true # true for false AND for missing
msg := sprintf("bucket %v is not encrypted", [input.name])
}not succeeds when the expression it wraps is false or undefined, which is exactly the coverage you wanted. Re-run against all three inputs (encrypted, unencrypted, missing) and confirm the last two now produce a message.
4. Iterate over a collection
Real inputs are lists. some ... in ... binds a variable to each element in turn, and because the rule is a set rule, every element that satisfies the body contributes its own message.
buckets.rego:
package storage
deny contains msg if {
some bucket in input.buckets # iterate; `bucket` is bound per element
not bucket.encryption.enabled == true
msg := sprintf("bucket %v is not encrypted", [bucket.name])
}
# A second, independent check over the same collection.
deny contains msg if {
some bucket in input.buckets
bucket.public == true
msg := sprintf("bucket %v is public", [bucket.name])
}There is no loop counter, no break, and no accumulator variable. You describe what a violation looks like and OPA finds every one of them.
buckets.json, three buckets in one document:
{ "buckets": [
{ "name": "prod-invoices", "encryption": { "enabled": true }, "public": false },
{ "name": "dev-scratch", "encryption": { "enabled": false }, "public": false },
{ "name": "web-assets", "public": true }
] }Evaluate the new policy against the list:
opa eval --format pretty -d buckets.rego -i buckets.json 'data.storage.deny'
It prints a set of three messages: bucket dev-scratch is not encrypted, bucket web-assets is not encrypted and bucket web-assets is public. prod-invoices breaks neither rule and adds nothing, and web-assets, which has no encryption setting at all, gets a message from each rule.
5. Gate a real Terraform plan with Conftest
With a real plan, it stops being a toy. Terraform can export its plan as JSON, and that JSON is just another input document. Run the commands below in the folder that holds your Terraform configuration, then copy the tfplan.json they write into the folder you run this page's other commands from: the policy folder below goes there too, and Conftest reads both from that folder. The first command writes the plan to a file, and the second converts it to JSON:
terraform plan -out=tfplan.binary terraform show -json tfplan.binary > tfplan.json
The interesting key is resource_changes: an array where each entry has an address, a type, a change.actions list, and change.after holding the resource as it will exist. The policy below checks one resource type, aws_s3_bucket_public_access_block, which holds an S3 bucket's settings for blocking public access, and requires its block_public_acls setting, which makes S3 refuse requests that would set a public ACL (access control list, an older way of granting access to a bucket or an object). policy/s3.rego:
package main # Conftest looks in `main` by default
deny contains msg if {
some rc in input.resource_changes
rc.type == "aws_s3_bucket_public_access_block"
# Only judge resources that will exist afterwards. A destroy has
# change.after == null; reading a field off null is undefined, and
# `not` turns undefined into a match, so without this line deleting
# the resource would be reported as a violation.
not "delete" in rc.change.actions
not rc.change.after.block_public_acls == true
msg := sprintf("%v does not block public ACLs", [rc.address])
}Conftest wraps OPA and knows how to read plan JSON, YAML, Dockerfiles, and more. Install it, run the policy against the plan, and print the exit code:
brew install conftest conftest test --policy policy/ tfplan.json echo $?
The exit code is 0 when there are no denials and 1 when there is at least one. This is your CI gate. Read the output as well as the exit code. A policy that fails to load also exits 1, so a syntax error looks exactly like a denial to a gate that checks only $?.
6. Unit-test the policy itself
A policy is code that decides whether other code ships. Untested, it is the least trustworthy thing in the pipeline. OPA has a test runner built in: any rule named test_* is a test, and it passes if it evaluates to true.
policy/s3_test.rego:
package main
# `with input as` swaps in a fake document for the duration of one expression.
test_denies_bucket_that_allows_public_acls if {
count(deny) == 1 with input as {
"resource_changes": [{
"address": "aws_s3_bucket_public_access_block.bad",
"type": "aws_s3_bucket_public_access_block",
"change": {"actions": ["create"], "after": {"block_public_acls": false}},
}]
}
}
# The direction people forget. Without this, a policy that denies
# EVERYTHING passes the test above and looks perfectly healthy.
test_allows_compliant_bucket if {
count(deny) == 0 with input as {
"resource_changes": [{
"address": "aws_s3_bucket_public_access_block.good",
"type": "aws_s3_bucket_public_access_block",
"change": {"actions": ["create"], "after": {"block_public_acls": true}},
}]
}
}Run the tests. -v names each test instead of printing only a tally.
opa test policy/ -v
7. Format, check, and lint
opa fmt -w rewrites the files in place, the way gofmt does for Go. opa check --strict rejects unused variables, shadowed names, and other things that parse but almost always mean a bug.
opa fmt -w policy/ opa check --strict policy/
Regal is a dedicated Rego linter and catches idiom problems opa check does not. Install it and lint the same folder:
brew install regal regal lint policy/
Run against this page's own policy/ directory after opa fmt, Regal reports five findings and no bugs: the package name does not mirror the directory, the tests share package main with the policy instead of living in main_test, and there is no entrypoint annotation. Conftest's main default explains the first two. Treat each as a convention to adopt, or to switch off in Regal's configuration on purpose.
Put opa check --strict and opa test in CI next to the gate itself. A policy repository where the policies are not tested is a repository that will eventually block a deploy for the wrong reason, and the fastest way to get policy-as-code removed from a pipeline is to have it be wrong once at a bad moment.
Hands-on exercises
Do these against the files you built above. Each one has a trap in it that this page has already warned you about at least once.
Write a rule that denies any EC2 instance in a Terraform plan whose metadata_options block does not set http_tokens to "required". That setting is what forces IMDSv2, and a missing metadata_options block is the default-insecure case that matters most.
Show the answer
deny contains msg if {
some rc in input.resource_changes
rc.type == "aws_instance"
not "delete" in rc.change.actions
not rc.change.after.metadata_options[0].http_tokens == "required"
msg := sprintf("%v does not require IMDSv2", [rc.address])
}The not ... == "required" form is doing the real work. If you wrote rc.change.after.metadata_options[0].http_tokens == "optional" you covered the explicitly-bad case and missed the far more common one where the block is absent entirely.
Note the [0]. In plan JSON a nested block such as metadata_options is a list, even when it can appear only once. Without the index, metadata_options.http_tokens is undefined on every instance, and the not flags the compliant ones too.
Your Terraform plan opens SSH (port 22) to 0.0.0.0/0, and this rule never fires against it. Find out why without changing the input.
deny contains msg if {
some rc in input.resource_changes
rc.type == "aws_security_group_rule"
rc.change.after.cidr_blocks[_] == "0.0.0.0/0"
rc.change.after.from_port = 22
msg := sprintf("%v exposes SSH to the internet", [rc.address])
}Show the answer
Before you debug the logic, prove the iteration is finding anything at all. An empty result, [], from the first query below tells you nothing. The second lists the resource types that are in the plan, which may not be the ones your rule names.
opa eval --format pretty -d policy/ -i tfplan.json \ 'data.main.deny' opa eval --format pretty -i tfplan.json \ '[rc.type | some rc in input.resource_changes]'
If the second query lists aws_vpc_security_group_ingress_rule and no aws_security_group_rule, that is the answer. The plan defines its SSH rule with the newer resource, which takes a single cidr_ipv4 string instead of a cidr_blocks list. A type filter that names a type the plan does not contain produces an empty iteration and therefore an empty deny set, forever, with no error. Against a plan that does use aws_security_group_rule, the rule fires as intended.
The single = on the port line is a separate smell, not the bug. = is unification: with both sides known, as here, it compares exactly as == would, but when one side is an unbound variable it binds instead, and the line always succeeds. Use == to compare and := to assign. Regal flags this line ("Prefer == for equality comparison"); opa check --strict does not.
Break a copy, so that the files the other exercises use stay as they are. This copies your policy folder, tests included, to a new folder named broken:
cp -r policy broken
Take the rule in broken/s3.rego, your copy of the one you wrote in step 5, and deliberately break it so that it denies everything: delete its conditions and leave only the some line and the message. Now run your existing tests against the copy, with opa test broken/ -v. Which of them fail, and what does that tell you about the tests you wrote before reading this?
Show the answer
Only test_allows_compliant_bucket fails. The deny-direction test still passes, because a rule that denies everything also denies the bad input.
This is the same shape as testing a firewall by confirming it blocks traffic: a correctly configured firewall and a completely broken one produce identical evidence. Every policy needs at least one test asserting that a compliant input produces no findings, and that is the test people skip, because writing it feels like testing that nothing happened.
Harder. Write a rule that denies when an IAM policy document grants "Action": "*" on "Resource": "*", handling the fact that both fields may be either a string or an array of strings.
Show the answer
package main
# A helper that normalises "string or array of strings" into a set.
# Two rules with the same name and different bodies: whichever one is
# defined for the given input wins. This is Rego's answer to overloading.
as_set(x) := {x} if is_string(x)
as_set(x) := {v | some v in x} if is_array(x)
deny contains msg if {
some stmt in input.Statement
stmt.Effect == "Allow"
"*" in as_set(stmt.Action)
"*" in as_set(stmt.Resource)
msg := "statement grants Action * on Resource *"
}{v | some v in x} is a set comprehension: read it as "the set of every v such that v is in x". Comprehensions are how you build a value in Rego without a loop, and this normalise-then-compare pattern shows up constantly, because the AWS IAM document schema is polymorphic in five different places.
Common mistakes
- Copying pre-1.0 syntax.
deny[msg] { ... }is the old form and will not parse on OPA 1.x. If a blog post's Rego has noifkeyword, it predates December 2024.opa fmt --rego-v1rewrites old files for you. - Treating undefined as false. Covered twice above because it is worth it. Reach for
not x == yrather thanx != ywhen a missing field should count as a violation. - Judging resources that are being destroyed. A Terraform plan's
resource_changesincludes deletions, andchange.afterisnullfor those. Filter onchange.actionsor your gate will report findings about resources that are on their way out. - Only testing the deny direction. A policy that denies everything passes every deny test you will ever write.
- Forgetting that Conftest defaults to package
main. Policies inpackage storageare silently not evaluated unless you pass--namespace storageor--all-namespaces. Zero findings and zero policies evaluated both exit 0, and only the tally line, which reads0 testswhen nothing was evaluated, tells them apart. - Skipping
opa check --strictand Regal.opa check --strictrejects an unused variable, and Regal flags a single=where you meant==. A typo in a field name passes both, because a misspelled field is just an undefined reference, so only a test with a realistic input catches it.
Where next
- CEL is the other policy expression language you will meet, and it is now built into Kubernetes admission. The comparison is worth making directly.
- IAM policy languages covers the AWS IAM grammar that Exercise 4 pokes at, plus Cedar.
- Kubernetes security for where Gatekeeper fits against the built-in admission controllers.
- Kyverno policies for the other Kubernetes admission engine, whose policies are Kubernetes resources with CEL inside, tested with its own CLI.
- Terraform and CI/CD security for wiring the Conftest gate into a pipeline that people cannot route around.
- The Rego policy reference and the Rego Playground, which shares a link to a live policy and is the fastest way to ask someone for help.
