anyPattern to express a logical OR inside a single validation rule so the rule accepts a resource if it matches any one of the supplied patterns.
Scenario: enforce non-root containers
- Requirement: All containers must run as a non-root user.
- Two valid developer models:
- Set
runAsNonRoot: trueat the Pod-levelsecurityContext(pod default). - Or set
runAsNonRoot: trueon every container (container-level).
- Set

pattern typically describes one structural variant. Combining both structures into one pattern is either impossible or results in a very complex pattern. anyPattern solves this cleanly by providing multiple alternative patterns; Kyverno passes validation if any pattern matches.
Why this policy must handle two cases
-
Problem 1 — override risk:
- A Pod-level default (
spec.securityContext.runAsNonRoot: true) can be overridden by a container settingsecurityContext.runAsNonRoot: false. The policy must prevent containers from disabling a safe pod default.
- A Pod-level default (
-
Problem 2 — missing default:
- If there is no pod-level
runAsNonRootdefault, every container (and initContainer) must explicitly setrunAsNonRoot: true. The policy must validate per-container declarations.
- If there is no pod-level
- Accept the Pod if either:
- The Pod has
spec.securityContext.runAsNonRoot: trueand no container (or initContainer) setsrunAsNonRoot: false, or - Every container and initContainer explicitly sets
securityContext.runAsNonRoot: true.
- The Pod has
anyPattern exists.
How anyPattern works
- Place
anyPatterninside a rule’svalidateblock. anyPatternaccepts a YAML list of alternative patterns.- Kyverno evaluates patterns sequentially; validation succeeds on the first matching pattern. The resource is rejected only if it fails to match every pattern in the list.

A Kyverno rule must use either a single
pattern or anyPattern. Do not combine pattern and anyPattern in the same rule.- The example below shows two alternative patterns inside
anyPattern:- Pattern A: Enforce a pod-level default and prevent container overrides.
- Pattern B: Require per-container
runAsNonRoot: truewhen no pod default exists.
Notes and tips
- Use the optional presence marker (
=) when you need to express conditional requirements for keys that may or may not exist (e.g.,=(initContainers)). - Keep
messagedescriptive so users know how to fix failures (pod-level default vs. per-container settings). anyPatternis especially useful when the same valid configuration can be expressed in multiple Kubernetes locations (e.g., pod vs container).
- Kyverno docs: https://kyverno.io/docs/
- Kubernetes securityContext: https://kubernetes.io/docs/tasks/configure-pod-container/security-context/
anyPattern keeps your validation rules concise while allowing multiple valid configuration models for the same requirement.