Skip to main content
In this lesson you’ll learn how to use operators in Kyverno validate rules. We’ll walk through two practical ClusterPolicy examples:
  • Enforce a minimum replica count for Deployments using comparison operators.
  • Block Deployments created in the default namespace using the not (!) operator.
These examples use Kyverno pattern-based validation to express flexible constraints without hardcoding exact values.

1) Enforce minimum replica count

This ClusterPolicy validates Deployments and enforces that spec.replicas is greater than or equal to 2. The comparison operator is expressed as a string inside the pattern field.
Key points:
  • failureAction: Enforce blocks resources that don’t meet the policy.
  • pattern.spec.replicas: ">=2" lets Kyverno accept any numeric value >= 2 (no exact value required).
If you match on replicas, Kyverno may warn about the scale subresource not being included in the policy. This is informational only and doesn’t change validation behavior, but add subresources to your match block if you also want to handle scale subresource requests.
When using numeric operators in Kyverno pattern values, put the operator and the number in a string (for example ">=2"). This enables comparison-style validation in patterns.
Apply the policy:
Expected output:
Try creating a Deployment that violates the policy (replicas = 1):
Expected admission error:
Now create a compliant Deployment (replicas = 3):
Expected output:
This demonstrates how Kyverno’s comparison operators allow enforcing minimum replica counts without requiring fixed replica values.

2) Disallow using the default namespace

This ClusterPolicy prevents Deployments from being created in the default namespace. It uses the not operator (!) in the pattern value to assert that metadata.namespace must not equal default.
Notes:
  • pattern.metadata.namespace: "!default" asserts that the namespace value must not be default.
  • failureAction: Enforce blocks requests that attempt to create Deployments in the default namespace.
Apply the policy:
Expected output:
If you try to create a Deployment without specifying a namespace (which defaults to default), it will be rejected:
Expected admission error:
To comply with the policy, create a different namespace and deploy there:
Expected output:
Using the -n flag or specifying metadata.namespace in manifests ensures resources are placed into allowed namespaces.

Summary

This lesson demonstrated two ways to use operators inside Kyverno pattern validations: These pattern operators let you express flexible, readable validation rules without hardcoding exact values. Use comparison operators for numeric constraints and the not operator (!) to exclude specific values.

Watch Video

Practice Lab