Gatekeeper splits policy definition into two separate Kubernetes objects. This separation is the most important concept to understand, and it's also the most common source of confusion for beginners.
The Analogy: Function Definition vs. Function Call
Think of it like writing a function in code:
# Function DEFINITION — the logic, reusable
def requires_label(resource, label_name):
return label_name in resource.metadata.labels
# Function CALLS — applying the logic with specific arguments
requires_label(namespace, "cost-center")
requires_label(namespace, "owner")
requires_label(namespace, "environment")
Gatekeeper works the same way.
1. ConstraintTemplate (The Logic — the Definition)
A ConstraintTemplate is a Kubernetes Custom Resource Definition (CRD) that contains two things:
- The Rego code that defines what a violation looks like.
- A schema for the parameters that Constraints can pass to the logic.
When you apply a ConstraintTemplate, Gatekeeper dynamically creates a new CRD in your cluster. For example, applying a template named K8sRequiredLabels creates a new resource type called K8sRequiredLabels that you can then instantiate.
The template itself enforces nothing. It just teaches Gatekeeper a new capability.
2. Constraint (The Arguments — the Call)
A Constraint is an instance of a ConstraintTemplate. It specifies:
match: Which resources to apply the policy to (by kind, namespace, label selector, etc.).parameters: The specific values to pass to the Rego logic (e.g., which label names are required).enforcementAction: What to do on violation —deny,dryrun, orwarn.
Why Separate Them?
You write one generic K8sRequiredLabels template, and then create many different Constraints from it — without duplicating any Rego code:
K8sRequiredLabels template
├── Constraint: namespaces-need-cost-center (labels: ["cost-center"])
├── Constraint: pods-need-owner (labels: ["owner"])
└── Constraint: deployments-need-environment (labels: ["environment"])
This is the policy library model. The open-source Gatekeeper Policy Library on GitHub provides dozens of pre-built templates (no-privileged-containers, required-labels, allowed-repos, etc.) that you can use immediately by just writing Constraints.