match and exclude statements in a Kyverno policy to enforce labels selectively.
Goal
- Require a Pod to have an
envlabel when it is created in themonitoringnamespace. - Exempt Pods that have the
team=operationslabel (those Pods are excluded from the policy).
match block narrows the policy scope to Pods in the monitoring namespace. The exclude block creates an exception for Pods with the team: operations label.
monitoring namespace (if it doesn’t exist):
match and exclude interact.
Test 1 — Pod without
env label (should be blocked)
Create a Pod in the monitoring namespace without the env label and without the team label. This Pod matches the match criteria and is not excluded, so the policy should deny it.
Attempt to create the Pod:
teams=operations instead of team=operations), the Pod will still be evaluated by the policy and denied:
team=operations (should be allowed)
Now create the Pod with the correct excluding label key team=operations. Because the exclude selector matches this Pod, the policy will not be applied to it and creation should succeed even though it lacks the env label.
matchnarrows policy scope to specific resources (here: Pods in themonitoringnamespace).excludedefines exceptions so matched resources with certain labels are skipped (here:team=operations).- A Pod that matches
matchand is not excluded is validated by thevalidaterule and rejected if it doesn’t meet the pattern. - Label keys must be exact — typos like
teamsvsteamwill prevent exclusion and cause the policy to apply.
Use
kubectl run ... --restart=Never to create an actual Pod (rather than a Deployment) for these tests. Also double-check label key names to ensure exclusions work as expected.