ConstraintTemplate
Defines reusable policy logic and schema for constraints.
Interactive guide to policy enforcement with ConstraintTemplates, Constraints, validating admission, and audit mode.
Gatekeeper adds policy-as-code controls to admission. It is most useful when you clearly separate reusable policy logic from the concrete policy instances that enforce it.
k8s/labs/security/gatekeeper/constraint-template.yaml — Gatekeeper ConstraintTemplate defining reusable Rego policy logic.k8s/labs/security/gatekeeper/constraint.yaml — Constraint CR that instantiates and scopes the template.k8s/labs/security/gatekeeper/compliant-pod.yaml — Sample Pod that satisfies the constraint.k8s/labs/security/gatekeeper/noncompliant-pod.yaml — Sample Pod expected to be denied by admission (policy violation demo).Defines reusable policy logic and schema for constraints.
Applies a specific policy instance to a set of resources.
Gatekeeper can both block non-compliant resources and audit the cluster for drift.
apiVersion: templates.gatekeeper.sh/v1
kind: ConstraintTemplate
metadata:
name: k8srequiredlabels
spec:
crd:
spec:
names:
kind: K8sRequiredLabels
validation:
openAPIV3Schema:
properties:
labels:
type: array
items:
type: string
targets:
- target: admission.k8s.gatekeeper.sh
rego: |
package k8srequiredlabels
violation[{"msg": msg}] {
provided := {label | input.review.object.metadata.labels[label]}
required := {label | label := 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: all-must-have-owner
spec:
match:
kinds:
- apiGroups: [""]
kinds: ["Pod"]
parameters:
labels:
- "owner"
- "environment"
# This Pod will be REJECTED:
apiVersion: v1
kind: Pod
metadata:
name: bad-pod
labels:
app: myapp # Missing "owner" and "environment"
spec:
containers:
- name: nginx
image: nginx
# Error: admission webhook denied the request:
# [all-must-have-owner] Missing required labels: {"environment", "owner"}
# List all ConstraintTemplates
kubectl get constrainttemplates
# List all Constraints
kubectl get constraints
# Check violations in a Constraint
kubectl describe k8srequiredlabels all-must-have-owner
# Check Gatekeeper audit results
kubectl get constraint -o yaml | grep violations -A 10
| Component | Role | Analogy |
|---|---|---|
| ConstraintTemplate | Reusable policy definition | Blueprint |
| Constraint | Concrete policy instance with scope | Applied policy rule |
Reject privileged containers, unsafe host access, or missing required settings.
Enforce labels, naming conventions, or namespace rules.
Use audit mode to identify policy drift without immediately blocking workloads.