Policy as Code: Where Rules Run
A policy is a rule about what is allowed: "S3 buckets are private", "pods don't run as root", "only the release workflow may deploy to production", "every resource has an owner tag". Policy as code means writing those rules in a language a machine evaluates, keeping them in Git, testing them, and running them automatically wherever changes happen.
One engine, many enforcement points
The Open Policy Agent (OPA, a CNCF graduated project) separates the decision from the enforcement. Some software asks OPA a question with a JSON document (input), OPA evaluates the policies (written in Rego) together with reference data, and returns a JSON answer. What happens next is up to the caller.
input (JSON) policy (Rego) + data (JSON)
caller ─────────────────────────► OPA ◄─────────────────────────────────────
◄───────── decision (JSON: allow/deny, messages) ─────────The same rule can then be enforced at several points, each catching problems earlier or more reliably:
| Where | Tool | Input | Catches |
|---|---|---|---|
| developer laptop | pre-commit + conftest |
files being committed | mistakes before review |
| CI, on config | conftest test |
Kubernetes YAML, Dockerfiles, .tf files |
violations in the change itself |
| CI, on plans | conftest test plan.json |
terraform show -json output |
what will actually change, after modules and variables are resolved |
| cluster admission | Gatekeeper, Kyverno, ValidatingAdmissionPolicy | each API request | anything that bypassed CI (kubectl apply by hand) |
| runtime / services | OPA as a sidecar or library, Envoy ext_authz | HTTP requests, tokens | authorization decisions in applications |
| audit | Gatekeeper audit, Kyverno reports, cloud config rules | existing resources | drift and pre-existing violations |
CI checks are fast feedback; admission is the guarantee. Running the same policies in both places (In the Cluster) means a developer sees in their pull request exactly the error the cluster would give.
A model of a policy engine
Strip away the syntax and a policy engine is a set of rules, each turning an input into zero or more violation messages, plus a decision on top. This is what Rego's deny contains msg if { … } rules mean, and what Conftest reports:
def no_public_buckets(doc):
for name, b in doc.get("aws_s3_bucket", {}).items():
if b.get("acl") in ("public-read", "public-read-write"):
yield f"aws_s3_bucket.{name} is public ({b['acl']})"
def owner_tag(doc):
for rtype, resources in doc.items():
for name, r in resources.items():
if "owner" not in r.get("tags", {}):
yield f"{rtype}.{name} has no owner tag"
def encrypted_db(doc):
for name, db in doc.get("aws_db_instance", {}).items():
if not db.get("storage_encrypted", False):
yield f"aws_db_instance.{name} is not encrypted"
POLICIES = {"deny": [no_public_buckets, encrypted_db], "warn": [owner_tag]}
def evaluate(doc):
result = {level: [m for rule in rules for m in rule(doc)] for level, rules in POLICIES.items()}
result["allow"] = not result["deny"]
return result
change = {
"aws_s3_bucket": {"exports": {"acl": "public-read", "tags": {"owner": "links"}},
"logs": {"acl": "private"}},
"aws_db_instance": {"main": {"storage_encrypted": False, "tags": {"owner": "links"}}},
}
r = evaluate(change)
for level in ("deny", "warn"):
for m in r[level]:
print(f"{level.upper():4} {m}")
print("allowed:", r["allow"])DENY aws_s3_bucket.exports is public (public-read)
DENY aws_db_instance.main is not encrypted
WARN aws_s3_bucket.logs has no owner tag
allowed: False
Three ideas carry over to every tool in this section:
- Rules produce messages, not just true/false. A good message names the resource and says how to fix it.
- Levels:
denyblocks,warninforms. New rules start as warnings, then become denials once existing violations are fixed. - The engine doesn't know Terraform or Kubernetes. It sees JSON. The work is in knowing the shape of that JSON (a plan, a manifest, an admission request).
Rego v1
OPA 1.0 (December 2024) made the Rego v1 syntax the default: rules need if, multi-value rules need contains, and in/every are keywords. Old policies in v0 syntax fail to parse:
cat > old.rego <<'REGO'
package main
deny[msg] {
input.kind == "Pod"
msg := "bare Pods are not allowed"
}
REGO
opa check old.rego; echo "exit $?"
echo "--- the same rule in Rego v1"
cat > new.rego <<'REGO'
package main
deny contains msg if {
input.kind == "Pod"
msg := "bare Pods are not allowed"
}
REGO
opa check new.rego && echo "ok"2 errors occurred during loading:
old.rego:3: rego_parse_error: `if` keyword is required before rule body
old.rego:3: rego_parse_error: `contains` keyword is required for partial set rules
exit 1
--- the same rule in Rego v1
ok
Most blog posts and many policy libraries still show v0 syntax. opa check --v0-compatible and opa fmt --v0-v1 help migrate; this course uses v1 throughout (OPA 1.21, Conftest 0.71).
Other policy languages
| Engine | Language | Typical use |
|---|---|---|
| OPA / Conftest / Gatekeeper | Rego | anything JSON-shaped; cross-tool policies |
| Kyverno | YAML patterns, CEL | Kubernetes-only, YAML-native teams (In the Cluster) |
| Kubernetes ValidatingAdmissionPolicy | CEL | built-in admission rules without a webhook (Admission Controllers) |
| Checkov, Trivy misconfiguration, KICS | built-in rule packs (Python/Rego) | ready-made IaC best practices (Toolkit) |
| HashiCorp Sentinel | Sentinel | Terraform Cloud/Enterprise policy sets |
| AWS SCPs, Azure Policy, GCP Org Policy | JSON | cloud-side guardrails that no tool can bypass |
Go further: Policy as Code for IaC, and Drift writes custom Rego checks and detects drift between code and account.
Test yourself
What does OPA return to its caller?
- An HTTP 403 automatically
- A JSON decision; the caller decides how to enforce it
- A Terraform plan
- A Kubernetes Secret
Why check Terraform plan JSON rather than only .tf files?
- Plans are smaller
- The plan shows the resolved result of modules, variables and expressions: what will actually change
.tffiles can't be parsed- Plans contain no secrets
Which Rego v1 form defines a rule that collects deny messages?
deny[msg] { … }deny contains msg if { … }deny := msg { … }rule deny(msg) { … }