Skip to main content
In this lesson we cover Kyverno’s forEach loop—a concise, declarative way to validate every item in a list inside a Kubernetes resource (for example, 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 forEach evaluates a JMESPath expression that selects a list from the admission request, then applies a validation clause to each element in that list.
Use case: Alex and the registry policy
  • 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 initContainers and containers, both of which must be validated.
Example Pod to validate:
Without a loop you’d need separate rules for each index. forEach handles this cleanly in a single rule. Example Kyverno validate rule using forEach
  • The rule below checks both initContainers and containers by looping over each list and validating the image field:
How forEach works
  1. Kyverno evaluates the list JMESPath expression (a string) against the admission request (for example: "request.object.spec.containers").
  2. If the expression returns an empty array or is missing, that loop entry is skipped.
  3. If items exist, Kyverno iterates them and exposes the current item as the implicit variable element.
  4. The validation clause (pattern, anyPattern, or deny) is evaluated against that element object—so fields on the container (like image) are referenced directly.
Condensed forEach example (two loops: initContainers and containers):
Important details and validation options
  • The list value 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 {{ }}.
  • element is the implicit variable representing the current item in the iteration (e.g., a single container object).
  • Validation clauses available inside a forEach entry:
Skeleton showing the different styles:
Summary
  • Use forEach to 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 using pattern, anyPattern, or deny.
  • A single rule with forEach can validate every item in a list, keeping policies concise, maintainable, and scalable.
The image provides a summary of "forEach Fundamentals," detailing the purpose, list, element, and logic related to validation logic application.
Links and references

Watch Video