Skip to main content
This lesson shows how to combine match and exclude statements in a Kyverno policy to enforce labels selectively. Goal
  • Require a Pod to have an env label when it is created in the monitoring namespace.
  • Exempt Pods that have the team=operations label (those Pods are excluded from the policy).
Policy definition Below is the ClusterPolicy that enforces this behavior. The 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.
Apply the policy Run the following to create the ClusterPolicy in your cluster:
Expected response:
Verify the policy:
Example output:
Create the monitoring namespace (if it doesn’t exist):
Expected response:
Tests Below are three tests demonstrating how 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:
Example denial from Kyverno webhook:
Test 2 — Pod with wrong label name (should also be blocked) If you accidentally add the wrong label key (for example teams=operations instead of team=operations), the Pod will still be evaluated by the policy and denied:
Expected response (same denial as above):
Test 3 — Pod with 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.
Expected response:
You can confirm the Pod exists:
Summary
  • match narrows policy scope to specific resources (here: Pods in the monitoring namespace).
  • exclude defines exceptions so matched resources with certain labels are skipped (here: team=operations).
  • A Pod that matches match and is not excluded is validated by the validate rule and rejected if it doesn’t meet the pattern.
  • Label keys must be exact — typos like teams vs team will 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.
Links and References

Watch Video

Practice Lab