pattern, making validation concise and declarative. We’ll cover three anchor types with short policy examples and test Pods:
- Conditional anchors
- Equality anchors
- Existence anchors
Anchors are a Kyverno pattern feature that let you express conditional validation without adding an extra configuration block.
failureAction: Enforce blocks resource creation when validation fails.Quick reference: anchor types
For full Kyverno anchor pattern syntax and examples, see the Kyverno documentation: https://kyverno.io/docs/writing-policies/validation-patterns/
1) Conditional anchors
Conditional anchors implement an if-then rule. The content inside parentheses is the “if” clause; a sibling key at the same hierarchy level is the “then” clause. Policy intent:- If a Pod mounts
/var/run/docker.sockvia ahostPathvolume, then the Pod must include labelallow-docker=true. failureAction: Enforceblocks non-compliant Pods.
- The
(spec) -> (volumes) -> (hostPath)path is the “if” condition — it matches when ahostPathvolume withpath: /var/run/docker.sockis present. - The sibling
metadata.labels.allow-dockeris the “then” clause and must matchtrue(string).
Policies with
failureAction: Enforce will block resource creation on non-compliance. Use background and failureAction carefully in production clusters.2) Equality anchors
Equality anchors use= to indicate the existence of an object. If the object exists, equality anchors let you place constraints on its child fields.
Policy intent:
- If a
hostPathvolume object exists in a Pod, then itspathmust not be/var/run/docker.sock.
=(spec)and=(volumes)assert that those objects exist; when they do, the child constraint applies.path: "!/var/run/docker.sock"uses Kyverno’s!operator to express “not equal”.
hostPath existed but its path did not match the forbidden value, the Pod passed validation.
3) Existence anchors
Existence anchors are applied to lists/arrays and assert that at least one element in the list matches a given pattern. This is ideal for requiring a Pod to include a specific sidecar or container image. Policy intent:- Verify that at least one container in the Pod uses the
nginximage.
- The policy iterates the
containerslist and accepts the Pod if any item hasimage: nginx. If none match, validation fails.
image: nginx), the policy is satisfied.
Recap
- Conditional anchors
( )create if-then rules where the “if” is an object pattern and the “then” is a sibling field. - Equality anchors
=check for the existence of an object and impose constraints on its children. - Existence anchors operate on lists and require at least one element to match the provided pattern.
Links and references
- Kyverno validation patterns: https://kyverno.io/docs/writing-policies/validation-patterns/
- Kyverno GitHub: https://github.com/kyverno/kyverno
- Kubernetes documentation: https://kubernetes.io/docs/