spec.containers and spec.initContainers in a Pod).
Why use forEach?
- Kubernetes objects often include arrays (containers, initContainers, volumeMounts, etc.). Writing index-specific rules for each element is error-prone and unscalable.
- Kyverno’s
forEachevaluates a JMESPath expression that selects a list from the admission request, then applies a validation clause to each element in that list.
- Alex, a platform engineer, must enforce a security requirement: every container image must come from the internal registry
trusted-registry.io. - A Pod can contain multiple
initContainersandcontainers, both of which must be validated.
- The rule below checks both
initContainersandcontainersby looping over each list and validating theimagefield:
- Kyverno evaluates the
listJMESPath expression (a string) against the admission request (for example:"request.object.spec.containers"). - If the expression returns an empty array or is missing, that loop entry is skipped.
- If items exist, Kyverno iterates them and exposes the current item as the implicit variable
element. - The validation clause (
pattern,anyPattern, ordeny) is evaluated against thatelementobject—so fields on the container (likeimage) are referenced directly.
- The
listvalue is a JMESPath expression written as a string. Do not wrap it in double curly braces.
Write JMESPath expressions directly as strings, for example:
"request.object.spec.containers". Do not use {{ }}.elementis the implicit variable representing the current item in the iteration (e.g., a single container object).- Validation clauses available inside a
forEachentry:
Skeleton showing the different styles:
- Use
forEachto iterate lists inside Kubernetes resources (e.g.,spec.containers,spec.initContainers) using JMESPath expressions. - For each iteration Kyverno exposes the current item as
element, and you validate that element usingpattern,anyPattern, ordeny. - A single rule with
forEachcan validate every item in a list, keeping policies concise, maintainable, and scalable.

- Kyverno documentation: https://kyverno.io/
- JMESPath specification: https://jmespath.org/
- Kubernetes Pods: https://kubernetes.io/docs/concepts/workloads/pods/containers/