$ run as a normal user# run as root (or with sudo)
Skills in this chapter
- Policy as code with OPA Gatekeeper
Know how Gatekeeper works
Gatekeeper is a validating admission webhook. A ConstraintTemplate holds the Rego logic; a Constraint applies it to certain objects with parameters.
Write a template and a constraint
Example: images must come from an allowed registry.
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata: { name: k8sallowedrepos }
spec:
crd:
spec:
names: { kind: K8sAllowedRepos }
validation:
openAPIV3Schema:
type: object
properties:
repos: { type: array, items: { type: string } }
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sallowedrepos
violation[{"msg": msg}] {
container := input.review.object.spec.containers[_]
not startswith_any(container.image, input.parameters.repos)
msg := sprintf("image %v is not from an allowed registry", [container.image])
}
startswith_any(img, repos) { startswith(img, repos[_]) }apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedRepos
metadata: { name: only-our-registry }
spec:
enforcementAction: deny
match:
kinds: [{ apiGroups: [""], kinds: ["Pod"] }]
namespaces: ["shop"]
parameters:
repos: ["ghcr.io/s0sta/", "acrshop2026.azurecr.io/"]Audit existing objects
Gatekeeper also checks objects that existed before the rule. Results are in the constraint's status.
kubectl get k8sallowedrepos only-our-registry -o jsonpath='{.status.totalViolations}'
kubectl describe k8sallowedrepos only-our-registry | grep -A5 ViolationsenforcementAction | Effect |
|---|---|
deny | Reject the request |
dryrun | Allow, only report in audit |
warn | Allow, show a warning |
At work
Roll out new rules with dryrun, fix the violations, then switch to deny.
Compare with Kyverno and ValidatingAdmissionPolicy
Same goal, other tools.
| Tool | Policy language | Notes |
|---|---|---|
| OPA Gatekeeper | Rego | Very flexible; a CKS topic |
| Kyverno | YAML | Easy to read; can also mutate and generate objects, verify image signatures |
| ValidatingAdmissionPolicy | CEL (built into Kubernetes) | No extra controller needed |