Iteration in Puppet using the future parser

People often ask me how do you iterate through an array in Puppet when you can do it easily in a template ?

Puppet uses declarative programming and is a domain specific language therefore it cannot do loops which you are probably used to doing in most languages.

Define iteration

For a while it has been possible to sort of iterate in Puppet manifests by using a define resource:

Which produces:

The name of the foo resource takes an array where each element calls the foo define.

Define resources are commonly used for apache configurations for example (see  http://docs.puppetlabs.com/learning/definedtypes.html).

However since every resource name must be unique, it is impossible to call a define twice, using the same values in the array.

Also if you want to iterate through an array inside a define, you’d have to call another define which can get messy.

Future Parser

Since Puppet version 3.2 experimental features are available http://docs.puppetlabs.com/puppet/3/reference/experiments_overview.html and it includes an array iteration feature !

Important note:

The future parser is an experimental feature and is not officially supported by Puppet Labs. It is not recommended for production environments, so enable it at your own risk and ensure you have gone through the new language restrictions at http://docs.puppetlabs.com/puppet/3/reference/experiments_future.html#new-language-restrictions
The non-capitalized variables compatibility and using variables in templates without @ prefixing (or scope.lookupvar) are two areas that need attention since there are quite a few Puppet Forge modules that still use them.

To enable the future parser on your puppetmaster, edit /etc/puppet/puppet.conf and add:

Restart the puppetmaster and check the syslog for any issues compiling catalogues for nodes. This is where you can find future parser compatibility issues.

To test array iteration with a puppet apply, it’s as simple as:

If you’re coding your Puppet modules in Geppetto, set the “Puppet target version” to “future” in the Preferences, to avoid the bad syntax highlighting.

Happy iterating !