OPA Gatekeeper Policy Enforcement
Enforce policies with OPA Gatekeeper on Kubernetes. ConstraintTemplates, Constraints, dry-run mode, audit, and common policies for security compliance.
π‘ Quick Answer: Install OPA Gatekeeper and create
ConstraintTemplateswith Rego policies. ApplyConstraintsto enforce rules like requiring resource limits, blocking privileged containers, and mandating labels. UseenforcementAction: dryrunto audit before enforcing.
The Problem
RBAC and Pod Security Standards provide basic guardrails, but organizations need custom policies: βall images must come from our approved registry,β βevery Deployment must have a team label,β βno containers can run as root.β OPA Gatekeeper lets you define and enforce any policy declaratively.
The Solution
Install Gatekeeper
helm repo add gatekeeper https://open-policy-agent.github.io/gatekeeper/charts
helm install gatekeeper gatekeeper/gatekeeper --namespace gatekeeper-system --create-namespaceConstraintTemplate: Require Labels
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8srequiredlabels
spec:
crd:
spec:
names:
kind: K8sRequiredLabels
validation:
openAPIV3Schema:
type: object
properties:
labels:
type: array
items:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8srequiredlabels
violation[{"msg": msg}] {
provided := {l | input.review.object.metadata.labels[l]}
required := {l | l := input.parameters.labels[_]}
missing := required - provided
count(missing) > 0
msg := sprintf("Missing required labels: %v", [missing])
}
---
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: require-team-label
spec:
enforcementAction: dryrun
match:
kinds:
- apiGroups: ["apps"]
kinds: ["Deployment"]
parameters:
labels: ["team", "env"]Block Privileged Containers
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8sblockprivileged
spec:
crd:
spec:
names:
kind: K8sBlockPrivileged
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8sblockprivileged
violation[{"msg": msg}] {
c := input.review.object.spec.containers[_]
c.securityContext.privileged == true
msg := sprintf("Privileged container not allowed: %v", [c.name])
}Audit Violations
# Check violations without enforcing
kubectl get k8srequiredlabels require-team-label -o yaml
# status.violations shows all non-compliant resources
# Switch from dryrun to enforce
kubectl patch k8srequiredlabels require-team-label \
--type=json -p='[{"op":"replace","path":"/spec/enforcementAction","value":"deny"}]'graph TD
TEMPLATE[ConstraintTemplate<br/>Define policy in Rego] --> CONSTRAINT[Constraint<br/>Apply to resources]
CONSTRAINT -->|dryrun| AUDIT[Audit Mode<br/>Report violations]
CONSTRAINT -->|deny| ENFORCE[Enforce Mode<br/>Block non-compliant]
CREATE[kubectl create deployment] --> GK[Gatekeeper Webhook]
GK -->|Check constraints| RESULT{Compliant?}
RESULT -->|Yes| ALLOW[β
Allowed]
RESULT -->|No| DENY[β Denied with reason]Common Issues
Gatekeeper blocking system resources: Add match.excludedNamespaces: [kube-system, gatekeeper-system] to constraints.
ConstraintTemplate not syncing: Check Rego syntax: kubectl describe constrainttemplate k8srequiredlabels. Rego syntax errors prevent the template from compiling.
Best Practices
- Start with dryrun β audit before enforcing
- Exclude system namespaces β never block kube-system
- Version ConstraintTemplates in Git β theyβre policy as code
- Audit dashboard β Gatekeeper exposes Prometheus metrics
- Common policies: required labels, image allowlist, no privileged, resource limits
Key Takeaways
- OPA Gatekeeper enforces custom policies on Kubernetes resources
- ConstraintTemplates define policies in Rego; Constraints apply them
- dryrun mode audits violations without blocking β always start here
- Policies as code: version control ConstraintTemplates alongside manifests
- Common use cases: required labels, image allowlists, no privileged containers

Recommended
Kubernetes Recipes β The Complete Book100+ production-ready patterns with detailed explanations, best practices, and copy-paste YAML. Everything in one place.
Get the Book βLearn by Doing
CopyPasteLearn β Hands-on Cloud & DevOps CoursesMaster Kubernetes, Ansible, Terraform, and MLOps with interactive, copy-paste-run lessons. Start free.
Browse Courses βπ Deepen Your Skills β Hands-on Courses
Courses by CopyPasteLearn.com β Learn IT by Doing
