
purpose: production. This prevents accidental or untracked Namespace creation and is an ideal use case for a Kyverno validate rule.
Below we build a cluster-scoped policy step-by-step to enforce this requirement.
ClusterPolicy: require-ns-purpose-label
We useClusterPolicy because the rule must apply to all Namespaces regardless of where they are created.
How the pattern works
- Kyverno compares the incoming Namespace resource to the
pattern. - If the pattern is present and matches (exact
purpose: production), Kyverno allows the request. - If the pattern is missing, the label value differs, or the labels block is absent, Kyverno rejects the request with the provided message.
Compliant example
A Namespace manifest that satisfies the policy:metadata.labels.purpose: production and allow the Namespace creation.
Non-compliant example
A Namespace manifest that fails validation:purpose is development (not production), Kyverno will block the request.
If validation fails, users receive immediate feedback when they run
kubectl apply, preventing misconfigurations before resources are created.Further reading
- Kyverno validation docs: https://kyverno.io/docs/writing-policies/validate/
- Kubernetes Namespaces: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/