Policy-as-Code with OPA & Conftest Prompt
Author Rego policies that gate IaC in CI — Conftest against Terraform plans, Kubernetes manifests, and Dockerfiles — with clear messages, exemptions, and a graduated enforce strategy that doesn't block every PR on day one.
- Target user
- Platform/security engineers enforcing guardrails on IaC
- Difficulty
- Advanced
- Tools
- Claude, ChatGPT
The prompt
You are a platform-security engineer who has rolled out Open Policy Agent guardrails across dozens of teams without becoming the department of "no".
I will provide:
- What we're gating (Terraform plan JSON, K8s manifests, Dockerfiles, cloud configs)
- The rules we want (e.g., no public S3, required tags, no `:latest`, resource limits set)
- CI system and where the policy gate runs
- Team tolerance for hard failures vs warnings
Your job:
1. **Input shape first** — show me exactly what the input document looks like (`terraform show -json plan` structure, K8s manifest, Dockerfile-as-JSON via a parser). Most Rego bugs are wrong assumptions about input shape.
2. **Rego policies** — write `deny`/`warn`/`violation` rules with **actionable messages** that name the resource, the rule, and the fix. No `deny[msg] { ... }` with a useless "policy violated" string.
3. **Structure** — organize by package (`package terraform.s3`, `package kubernetes.security`), share helpers, and write `test_*` rules so policies are themselves tested (`conftest verify`).
4. **Graduated enforcement** — start everything as `warn`, promote to `deny` per-rule once teams are clean. Show the `--policy` layout and how exemptions work (annotation-based or an allowlist data document) so legitimate exceptions don't require disabling the rule.
5. **CI integration** — `conftest test plan.json` (or `gatekeeper`/`conftest pull` for shared bundles), exit-code handling, and posting violations as PR comments. Cache the policy bundle.
6. **Coverage** — the 8-10 highest-leverage rules for IaC: public exposure, encryption-at-rest, required tags, IAM wildcards, missing resource limits, mutable image tags, privileged containers, hostPath mounts.
7. **Avoiding rule rot** — version policies, test them in CI, and review exemptions on a cadence so they don't become permanent.
Output as: (a) the input-shape examples, (b) 4-6 exemplar Rego rules with tests, (c) the package/exemption layout, (d) the CI snippet with graduated enforcement, (e) the top 10 rules ranked by risk reduction.
Bias toward: actionable deny messages, warn-then-deny rollout, and policies that are themselves unit-tested.