Writing Constraint Templates
You'll learn how to create reusable policy logic in Gatekeeper using ConstraintTemplates and the Rego language to enforce custom admission rules.
What Are ConstraintTemplates?
Think of a ConstraintTemplate as a policy blueprint or cookie cutter. Instead of writing admission rules from scratch every time, you define the template once with configurable parameters, then stamp out specific policy instances (Constraints) as needed. It's like creating a form letter where you fill in the blanks differently each time while the structure stays the same.
In Gatekeeper, ConstraintTemplates use Rego (OPA's policy language) to define the validation logic that examines Kubernetes resource requests.
Core Structure
A ConstraintTemplate has two main sections:
- CRD schema – Defines what parameters your policy accepts
- Rego code – Contains the actual validation logic
The template creates a new Custom Resource Definition (CRD) that you'll use to instantiate actual Constraints.
Basic Components
Your ConstraintTemplate defines:
spec.crd.spec.names.kind– The name of the Constraint type you're creatingspec.crd.spec.validation.openAPIV3Schema– Parameters users can configurespec.targets– Where to apply the policy (typicallyadmission.k8s.gatekeeper.sh)spec.targets[].rego– Your Rego validation rules
The Rego code checks incoming resources and returns violation messages when policies are breached. You access the resource being evaluated via input.review.object and your parameters via input.parameters.
Key Takeaway: ConstraintTemplates let you write reusable, parameterized policy logic once in Rego, then create multiple configured Constraint instances without duplicating code—making governance scalable and maintainable.