Implementing Constraints
What you'll learn: How to apply Constraint resources in OPA Gatekeeper to actively enforce security and compliance policies across your Kubernetes cluster.
Understanding Constraints
While Constraint Templates define the shape and logic of a policy rule, Constraints are the instances that actually enforce those rules. Think of Constraint Templates as cookie cutters—they define the shape—while Constraints are the actual cookies you bake and serve to your cluster.
A Constraint applies a template to specific resources, defining which namespaces or objects should be checked and what parameters to enforce.
How Constraints Work
When you create a Constraint resource:
- It references an existing Constraint Template by
kind - It specifies match criteria (which resources to evaluate)
- It provides parameters that customize the template's behavior
- Gatekeeper evaluates every matching resource against the policy
Common Use Cases
Required labels example: Enforce that all namespaces have an "owner" label:
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sRequiredLabels
metadata:
name: namespace-must-have-owner
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Namespace"]
parameters:
labels: ["owner"]
Allowed registries example: Only permit container images from approved registries:
apiVersion: constraints.gatekeeper.sh/v1beta1
kind: K8sAllowedRepos
metadata:
name: allowed-container-registries
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
parameters:
repos:
- "mycompany.registry.io"
- "docker.io/approved"
Once applied, Gatekeeper automatically blocks any resource creation or update that violates these constraints.
Key Takeaway: Constraints turn policy templates into active enforcement by specifying what to check and where to apply rules—transforming cluster governance from aspiration to automatic reality.