Chapter 5. OPA and Conftest
Why this
Static linters (kube-linter / kube-score / Checkov) are great. OPA/Conftest lets you add your org’s rules that those tools don’t cover or you want to phrase differently, and run them before admission.
1) Repo layout
policy/ k8s.rego infra/k8s/
your Deployment/Service/etc.
2) Policy (copy/paste)
Create policy/k8s.rego with three practical rules:
package main
# Input is a list of Kubernetes resources (YAML files parsed by conftest)
deny[msg] {
some i
input[i].kind == "Deployment"
some c
containers := input[i].spec.template.spec.containers
containers[c].image endswith ":latest"
msg := sprintf("Deployment %q uses :latest tag in container %q", [input[i].metadata.name, containers[c].name])
}
deny[msg] {
some i
input[i].kind == "Deployment"
some c
containers := input[i].spec.template.spec.containers
not containers[c].securityContext.runAsNonRoot
msg := sprintf("Deployment %q container %q missing runAsNonRoot: true", [input[i].metadata.name, containers[c].name])
}
deny[msg] {
some i
input[i].kind == "Deployment"
some c
containers := input[i].spec.template.spec.containers
not containers[c].resources.requests.cpu
not containers[c].resources.requests.memory
msg := sprintf("Deployment %q container %q missing CPU/Memory requests (and likely limits)", [input[i].metadata.name, containers[c].name])
}
You can extend this file over time (e.g., require readiness/liveness, forbid privileged, etc.).
3) Run Conftest (Dockerized, no local install)
From repo root:
mkdir -p artifacts
docker run --rm -v "$PWD":/work -w /work openpolicyagent/conftest:v0.56.0 \
test infra/k8s -p policy | tee artifacts/conftest.txt || true
- Exit code
0= all good; non-zero = at least onedenyfired. - Either way, the report is saved to
./artifacts/conftest.txt.
4) Makefile target (optional)
k8s-conftest: init
docker run --rm -v $(PWD):/work -w /work openpolicyagent/conftest:v0.56.0 \
test infra/k8s -p policy | tee artifacts/conftest.txt || true
5) Integrate with your flow
- Run
make k8s-audit k8s-conftestbeforemake cd. - Keep Conftest in WARN for Week 1–2; promote to BLOCK once noise is low.
Checklist
-
policy/k8s.regocommitted with at least 3 rules -
artifacts/conftest.txtproduced and reviewed - Violations fixed (or exceptions recorded) before deploy