Course contentsShow
← Cloud and Infrastructure
Lesson 1415 of 2,98928. Kubernetes SecurityFree lesson

Implementing Constraints

Applying Constraint resources to enforce specific policies across namespaces, such as required labels or allowed registries.

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:

  1. It references an existing Constraint Template by kind
  2. It specifies match criteria (which resources to evaluate)
  3. It provides parameters that customize the template's behavior
  4. 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.