- requiring specific labels on every Pod,
- restricting images to approved registries,
- disallowing the
:latestimage tag.
- ConstraintTemplate — defines a policy (registers a new CRD and contains Rego logic).
- Constraint — an instance of that policy (sets parameters, scope, and enforcement).
team and environment labels on Pods.
Important references:
- Gatekeeper documentation: https://open-policy-agent.github.io/gatekeeper/
- OPA/Rego language: https://www.openpolicyagent.org/docs/latest/policy-language/
- Kubernetes admission controllers: https://kubernetes.io/docs/reference/access-authn-authz/admission-controllers/
ConstraintTemplate — define the policy and CRD
Create a ConstraintTemplate that registers a new CRDRequiredLabels and embeds the Rego logic to detect missing labels. Save this as required-labels-template.yaml:
spec.crd.spec.names.kindcreates the CRD KindRequiredLabels.openAPIV3Schemavalidates the constraint parameters (labelsmust be an array of strings).targets.regocontains the Rego policy executed during admission; it compares required labels with provided labels and generates violations when labels are missing.
Constraint — instantiate the policy
Instantiate the policy by creating a Constraint of kindRequiredLabels. This configures parameters, scope, and the enforcement action. Save as required-labels-constraint.yaml:
enforcementAction:deny,dryrun, orwarn. Usedenyto block violating requests.match.kinds: scopes the constraint to core Pods.parameters.labels: the required label keys validated by the template schema.
Test: pod without required labels (expected to be denied)
Createtest-pod-no-labels.yaml:
Test: pod with required labels (expected to be admitted)
Createtest-pod-with-labels.yaml:
Dry-run mode: audit without breaking workloads
Before enforcing a blocking policy, usedryrun to discover existing violations safely. Patch the constraint to dryrun:
policy-test:
Start in
dryrun to discover existing violations, remediate resources where needed, and then switch to deny to fully enforce the policy. This staged rollout pattern reduces disruption.Summary
- ConstraintTemplate defines a policy: it registers a CRD and contains Rego logic.
- Constraint is a policy instance: it configures parameters, scope, and enforcement mode.
- Use
dryrunto audit and identify violations before enablingdeny. - Gatekeeper is an effective policy-as-code solution for Kubernetes: use it to enforce labels, image registries, tag policies, and other organizational rules.