Looping and iteration features help you write more succinct code, and use data more effectively.

Iteration functions

Iteration features are implemented as functions that accept blocks of code (lambdas). When a lambda requires extra information, pass it to a function that provides the information and to evaluate the code, possibly multiple times. This differs from some other languages where looping constructs are special keywords. In the Puppet code, they're functions.

Tip: Iteration functions take an array or a hash as their main argument, and iterate over its values.

These functions accept a block of code and run it in a specific way:

each - Repeats a block of code a number of times, using a collection of values to provide different parameters each time.

slice - Repeats a block of code a number of times, using groups of values from a collection as parameters.

filter - Uses a block of code to transform a data structure by removing non-matching elements.

map - Uses a block of code to transform every value in a data structure.

reduce - Uses a block of code to create a new value, or data structure, by combining values from a provided data structure.

with - Evaluates a block of code once, isolating it in its own local scope. It doesn’t iterate, but has a family resemblance to the iteration functions.

The each, filter, and map functions accept a lambda with either one or two parameters. Depending on the number of parameters, and the type of data structure you’re iterating over, the values passed into a lambda vary:

See the slice and reduce documentation for information on how these functions handle parameters differently.

Hashes preserve the order in which their keys and values were written. When iterating over a hash’s members, the loops occur in the order that they are written. When interpolating a hash into a string, the resulting string is also constructed in the same order.

For information about the syntax of function calls, see the functions documentation, or the lambdas documentation for information about the syntax of code blocks that you pass to functions.

Declaring resources

The focus of the Puppet language is declaring resources, so most people want to use iteration to declare many similar resources at once. In this example, there is an array of command names to be used in each symlink’s path and target. The each function makes this succinct.