- Enforce a minimum replica count for Deployments using comparison operators.
- Block Deployments created in the
defaultnamespace using the not (!) operator.
pattern-based validation to express flexible constraints without hardcoding exact values.
1) Enforce minimum replica count
This ClusterPolicy validates Deployments and enforces thatspec.replicas is greater than or equal to 2. The comparison operator is expressed as a string inside the pattern field.
failureAction: Enforceblocks 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.2) Disallow using the default namespace
This ClusterPolicy prevents Deployments from being created in thedefault namespace. It uses the not operator (!) in the pattern value to assert that metadata.namespace must not equal default.
pattern.metadata.namespace: "!default"asserts that the namespace value must not bedefault.failureAction: Enforceblocks requests that attempt to create Deployments in thedefaultnamespace.
default), it will be rejected:
-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 Kyvernopattern 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.
Links and References
- Kyverno Documentation: https://kyverno.io/
- Kyverno Policy Examples: https://kyverno.io/docs/writing-policies/
- Kubernetes Concepts — Namespaces: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/