Skip to main content
In this lesson we demonstrate how to use Kyverno’s 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 list field accepts a JMESPath expression (e.g., request.object.spec.containers) to identify the array to iterate over.
  • During each iteration a temporary variable named element is available to reference the current item being validated.
  • The pattern block is evaluated against each element. If any element fails the pattern match, the rule fails.
  • You can include multiple foreach entries in a single rule to validate different repeated fields (for example, both initContainers and containers) without creating separate rules.
Example: ClusterPolicy that enforces a trusted registry for every container image (including init containers)
Policy explanation
  • This is a ClusterPolicy, so it applies across the cluster to Pod resources.
  • preconditions prevents the rule from running on DELETE operations (key: "{{request.operation}}").
  • validationFailureAction: Enforce blocks Pod creation when the rule fails.
  • There are two foreach entries:
    • One iterates over request.object.spec.initContainers.
    • The other iterates over request.object.spec.containers.
  • Each pattern is applied to each element in the corresponding list; the image field must match trusted-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.
Apply the policy
Test: Pod that violates the policy This Pod uses busybox:latest from the public registry and should be rejected:
Expected rejection from the admission webhook:
The Pod is blocked because the container image does not match 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:
Expected successful creation:
Quick reference table Summary
  • foreach iterates over lists using a JMESPath expression (for example, request.object.spec.containers or request.object.spec.initContainers) and applies the pattern to each element.
  • Using foreach reduces duplication and simplifies rules that validate repeated elements.
  • Combining foreach with preconditions and validationFailureAction: Enforce provides a robust approach to block noncompliant resources.
Links and references

Watch Video

Practice Lab