Iteration and lambdas
Puppet language has historically been somehow limited in iterators, it didn't have explicit support for this till version 4.0. The old way of doing it is by the use of defined types. All Puppet resources can have an array as its title, which is equivalent to creating the same resource one time with each of the elements of the array.
This approach, although sometimes convenient and orthogonal with the rest of the language, has some limitations. First, only the title varies between each created resource, which limits the possibilities of the code in the iteration, and second, a defined type needs to be implemented just for the iteration; it can even happen that the type is defined far from the place where we want to iterate, thus over-complicating it and making it less readable. Here is an example:
define nginx::enable_site ($site = $title) { file { "/etc/nginx/sites-enabled/$site": ensure => link, target => "/etc/nginx/sites-available/$site", } } $sites = ['example.com', 'test.puppetlabs.com'] nginx::enable_site { $sites: }
In newer versions, the language includes support for lambda functions and some functions that accept these lambdas as parameters, allowing more explicit iterators, for example, to define resources:
$sites = ['example.com', 'test.puppetlabs.com'] $sites.each |String $value| { file { "/etc/nginx/sites-enabled/$site": ensure => link, target => "/etc/nginx/sites-available/$site", } }
To transform data, like selecting the sites that start with "test" from a list, use a code as follows:
$test_sites = $sites.filter |$site| { $site =~ /^test\./ }
The in operator
The in
operator checks whether a string is present in another string, an array, or in the keys of a hash. It is case sensitive:
if '64' in $::architecture if $monitor_tool in [ 'nagios' , 'icinga' , 'sensu' ]
Expressions combinations
It's possible to combine multiple comparisons with and
and or
:
if ($::osfamily == 'RedHat') and ($::operatingsystemrelease == '5') { [ ... ] } if (operatingsystem == 'Ubuntu') or ($::operatingsystem == 'Mint') { [ ...] }