OPA Policy as Code: Rego Rules, Gatekeeper & CI Enforcement Guide
Open Policy Agent (OPA) is a CNCF graduated general-purpose policy engine that decouples policy decisions from application code. Write authorization rules, Kubernetes admission policies, and infrastructure guardrails in Rego — a declarative language designed for expressing complex policy logic as testable, versionable code.
What is OPA and Policy as Code?
Policy as Code means expressing your authorization rules, compliance requirements, and infrastructure guardrails as code files that can be version-controlled, reviewed, and tested — just like application code. Without policy as code, authorization logic is scattered across application code, Kubernetes RBAC YAML, Terraform configurations, and tribal knowledge in ops runbooks. OPA provides a single engine that evaluates policies consistently across all these systems.
OPA answers one question: is this request allowed? Your application (or webhook, or CI pipeline) sends a JSON object describing what is happening, and OPA returns a policy decision based on your Rego rules and any external data you've loaded.
Rego Language Basics
# policy.rego — basic allow/deny
package myapp.authz
import rego.v1
# Default deny — undefined rules evaluate as false
default allow := false
# Allow if user is admin
allow if {
input.user.role == "admin"
}
# Allow GET requests to public paths
allow if {
input.method == "GET"
input.path[0] == "public"
}
# Allow users to access their own resources
allow if {
input.method == "GET"
input.path[0] == "users"
input.path[1] == input.user.id
} # Query OPA (input is passed as JSON)
echo '{
"input": {
"user": {"id": "alice", "role": "admin"},
"method": "DELETE",
"path": ["users", "bob"]
}
}' | opa eval -d policy.rego -I 'data.myapp.authz.allow'
# Output: {"result": [{"expressions": [{"value": true}]}]} OPA Playground and opa eval
# Install OPA
curl -L -o opa https://openpolicyagent.org/downloads/latest/opa_linux_amd64_static
chmod +x opa && sudo mv opa /usr/local/bin/
# Evaluate a policy from CLI
opa eval \
--data policy.rego \
--data data.json \
--input input.json \
'data.myapp.authz.allow'
# Start OPA as REST server
opa run --server --addr :8181 policy.rego data.json
# Query via REST API
curl -X POST http://localhost:8181/v1/data/myapp/authz/allow \
-H "Content-Type: application/json" \
-d '{"input": {"user": {"role": "admin"}, "method": "GET"}}' Kubernetes Gatekeeper: ConstraintTemplate Example
# Install Gatekeeper
kubectl apply -f https://raw.githubusercontent.com/open-policy-agent/gatekeeper/release-3.15/deploy/gatekeeper.yaml
# ConstraintTemplate — defines the policy logic
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: requiredlabels
spec:
crd:
spec:
names:
kind: RequiredLabels
validation:
openAPIV3Schema:
properties:
labels:
type: array
items: {type: string}
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package requiredlabels
violation[{"msg": msg}] {
provided := {label | input.review.object.metadata.labels[label]}
required := {label | label := input.parameters.labels[_]}
missing := required - provided
count(missing) > 0
msg := sprintf("Missing required labels: %v", [missing])
} # Constraint — applies the policy to Pods in production namespace
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: RequiredLabels
metadata:
name: pod-must-have-owner
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
namespaces: ["production"]
parameters:
labels: ["owner", "team", "environment"] OPA for API Authorization
// Express.js middleware — query OPA before processing requests
const axios = require('axios');
async function opaAuthz(req, res, next) {
const input = {
user: req.user, // from JWT middleware
method: req.method,
path: req.path.split('/').filter(Boolean),
resource: req.params.id,
};
const response = await axios.post('http://opa:8181/v1/data/myapp/authz/allow', {
input,
});
if (response.data.result !== true) {
return res.status(403).json({ error: 'Forbidden' });
}
next();
}
app.use('/api', opaAuthz); Testing Rego Policies
# policy_test.rego
package myapp.authz_test
import data.myapp.authz
test_admin_can_delete if {
authz.allow with input as {
"user": {"role": "admin"},
"method": "DELETE",
"path": ["users", "alice"],
}
}
test_viewer_cannot_delete if {
not authz.allow with input as {
"user": {"role": "viewer"},
"method": "DELETE",
"path": ["users", "alice"],
}
}
# Run tests
# opa test ./policies/ --verbose --coverage CI Integration
# .github/workflows/opa.yml
- name: Run OPA tests
uses: open-policy-agent/setup-opa@v2
with:
version: latest
- name: Test policies
run: opa test ./policies/ --coverage --format=json > coverage.json
- name: Check Terraform plan (Conftest)
run: |
terraform plan -out=plan.tfplan
terraform show -json plan.tfplan > plan.json
conftest test plan.json --policy policies/terraform/ OPA vs Kyverno vs Casbin
| Tool | Language | Kubernetes | API authz | Best for |
|---|---|---|---|---|
| OPA | Rego (declarative) | Via Gatekeeper | Yes | Multi-system policy |
| Kyverno | YAML | Native CRD | No | K8s-only, no Rego |
| Casbin | PERM model + CSV | No | Yes (library) | In-app RBAC/ABAC |
Related Products
on GumroadDeveloper Productivity Bundle
Stop rebuilding the same setup every project. 51 VSCode snippets, 40 Git aliases, 5 Docker Compose stacks, 5 GitHub Actions workflows, 5 README templates, and a dotfiles kit. Set up a professional dev environment in under an hour.
Buy on Gumroad →AI Prompt Engineering Toolkit
58 structured prompt templates for Claude, ChatGPT, and Gemini — organized by use case. Code Review, Debugging, Documentation, Architecture, and 10 model-specific tips. Stop writing prompts from scratch.
Buy on Gumroad →Developer Cheat Sheet Bundle
10 print-ready cheat sheets for the tools developers use every day: Git, Docker, Linux CLI, SQL, Regex, HTTP Status codes, VS Code shortcuts, Bash scripting, jq/JSON, and Markdown.
Buy on Gumroad →You Might Also Need
JSON Formatter & Validator
Format, beautify, and validate JSON online. Paste your JSON to instantly pretty-print it with 2-space, 4-space, or tab indentation. Minify JSON too. Free, runs in your browser.
Open free tool →
Regex Tester
Free regex tester. Test regular expressions against multiple strings with expected match/no-match assertions — see instant pass/fail results. Built-in presets for email, URL, IPv4, and phone. Pro: unl
Open free tool →
Base64 Encoder & Decoder
Free Base64 Encoder & Decoder. Convert text, images, and any file to Base64 and back. Supports URL-safe Base64, image data URIs, and file download from Base64. Runs 100% in your browser — no data sent
Open free tool →
More Free Tools
Related Articles
curl 深度使用手冊:API 測試從入門到進階
curl 是每位開發者必備的 CLI 工具。本文涵蓋 GET/POST/PUT/DELETE 請求、認證、header 設定、檔案上傳、除錯技巧,以及 REST API 測試的完整實戰範例。
Best AI Code Review Tools 2026: CodeRabbit, Sourcery, DeepCode & Bito Compared
Compare top AI code review tools for 2026: CodeRabbit, Sourcery, DeepCode, and Bito. Features, pricing, GitHub/GitLab integration, and choosing the right tool for your team.
AI Code Review Tools 2026: GitHub Copilot, CodeRabbit, Qodo Merge Ranked
Compare AI code review tools for 2026: GitHub Copilot code review, CodeRabbit, Qodo Merge, Sourcery, and PR-Agent. Pricing, accuracy, and GitHub integration.
AI Coding Tools Comparison 2026: GitHub Copilot vs Cursor vs Windsurf vs Cline
Comprehensive comparison of the best AI coding tools in 2026: GitHub Copilot, Cursor, Windsurf, and Cline. Pricing, features, model support, and real-world benchmarks.
AI Pair Programming in 2026: GitHub Copilot vs Cursor vs Claude Code
Master AI pair programming in 2026. Compare GitHub Copilot, Cursor, and Claude Code for autocomplete, chat, and agentic workflows. Includes setup guides and productivity tips.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$9/mo after trial · Cancel anytime
Want the full toolkit?
Get DevPlaybook Pro
Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →