foreach construct inside validation rules to iterate over lists of elements within a resource. foreach simplifies policy authoring for repeated fields such as containers, initContainers, and volumes by applying a pattern to each element in the specified list.
How foreach works
- The
listfield accepts a JMESPath expression (e.g.,request.object.spec.containers) to identify the array to iterate over. - During each iteration a temporary variable named
elementis available to reference the current item being validated. - The
patternblock is evaluated against eachelement. If any element fails the pattern match, the rule fails. - You can include multiple
foreachentries in a single rule to validate different repeated fields (for example, bothinitContainersandcontainers) without creating separate rules.
- This is a
ClusterPolicy, so it applies across the cluster toPodresources. preconditionsprevents the rule from running onDELETEoperations (key: "{{request.operation}}").validationFailureAction: Enforceblocks Pod creation when the rule fails.- There are two
foreachentries:- One iterates over
request.object.spec.initContainers. - The other iterates over
request.object.spec.containers.
- One iterates over
- Each
patternis applied to eachelementin the corresponding list; theimagefield must matchtrusted-registry.io/*(the wildcard allows any image path under that registry). - If any container or initContainer has an image that does not match the pattern, the rule will fail and the Pod will be rejected.
Using multiple
foreach entries inside a single rule lets you validate different repeated fields (like initContainers and containers) without writing separate rules.busybox:latest from the public registry and should be rejected:
trusted-registry.io/*.
Test: Pod that satisfies the policy
This Pod uses images from the trusted registry for both an init container and a main container and should be accepted:
Summary
foreachiterates over lists using a JMESPath expression (for example,request.object.spec.containersorrequest.object.spec.initContainers) and applies thepatternto eachelement.- Using
foreachreduces duplication and simplifies rules that validate repeated elements. - Combining
foreachwithpreconditionsandvalidationFailureAction: Enforceprovides a robust approach to block noncompliant resources.
- Kyverno foreach documentation: https://kyverno.io/docs/writing-policies/foreach/
- JMESPath query language: https://jmespath.org/
- Kubernetes admission webhooks: https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/