match blocks control which resources a policy evaluates. We’ll enforce that Pods and Deployments include a non-empty env label using a ClusterPolicy, then refine the rule to target a specific namespace.
Policy: require an env label
Create the following ClusterPolicy to validate that metadata.labels.env exists and is non-empty for Pods and Deployments:
matchselects which resources Kyverno evaluates (here: kinds Pod and Deployment).validate.patternenforces the presence and a non-empty value formetadata.labels.env.
The
?* pattern in Kyverno matches any non-empty string, ensuring the env label exists and is not empty.This policy uses
validationFailureAction: enforce, which will block resource creation or updates that don’t meet the rule. Use audit if you prefer non-blocking checks.Apply the policy
Apply the policy manifest and verify the ClusterPolicy is ready:Test the policy
- Create a Pod without labels (expected: rejected, because Pod is matched by the rule):
- Create a Deployment without the
envlabel (expected: rejected):
- Create a Pod with the
envlabel (expected: allowed):
env label for the matched kinds.
Scope the rule to a namespace
You can narrow thematch block to specific namespaces. The example below restricts enforcement to the restricted-ns namespace:
- Create a Pod in
restricted-nswithout labels (expected: rejected):
- Create a Pod in the
defaultnamespace without labels (expected: allowed, because it doesn’t match thenamespacesfilter):
Quick reference
Summary
- Use the
matchblock to control which resources Kyverno evaluates (kinds, namespaces, selectors). - Use
validate.patternto require fields—?*ensures a string is present and non-empty. - Adding
namespacestomatchscopes enforcement to specific namespaces (e.g.,restricted-ns) while leaving other namespaces unaffected.