Skip to main content
This guide demonstrates how Kyverno 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:
The key parts:
  • match selects which resources Kyverno evaluates (here: kinds Pod and Deployment).
  • validate.pattern enforces the presence and a non-empty value for metadata.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

  1. Create a Pod without labels (expected: rejected, because Pod is matched by the rule):
Example admission webhook response:
  1. Create a Deployment without the env label (expected: rejected):
Example error:
  1. Create a Pod with the env label (expected: allowed):
These steps confirm the policy enforces the env label for the matched kinds.

Scope the rule to a namespace

You can narrow the match block to specific namespaces. The example below restricts enforcement to the restricted-ns namespace:
Apply the updated policy and create the namespace:
Test the namespace-scoped behavior:
  • Create a Pod in restricted-ns without labels (expected: rejected):
Example webhook response:
  • Create a Pod in the default namespace without labels (expected: allowed, because it doesn’t match the namespaces filter):

Quick reference

Summary

  • Use the match block to control which resources Kyverno evaluates (kinds, namespaces, selectors).
  • Use validate.pattern to require fields—?* ensures a string is present and non-empty.
  • Adding namespaces to match scopes enforcement to specific namespaces (e.g., restricted-ns) while leaving other namespaces unaffected.

Watch Video

Practice Lab