Puppet Conditionals, Iteration and Lambdas: if, case, selectors, each, map and filter
if, elsif, else, unless
puppet
if $facts['os']['family'] == 'Debian' {
$web_package = 'apache2'
} elsif $facts['os']['family'] == 'RedHat' {
$web_package = 'httpd'
} else {
fail("Unsupported OS family: ${facts['os']['family']}")
}
package { $web_package:
ensure => installed,
}
unless $facts['is_virtual'] {
package { 'smartmontools': ensure => installed } # only on physical machines
}
| Truthiness | Detail |
| False values | false and undef only |
| True values | Everything else, including 0, '' (empty string) and empty arrays |
Gotcha: Unlike many languages, the empty string '' and the number 0 are true in Puppet. Test explicitly: if $name != '' or if $name =~ String[1].
case
puppet
case $facts['os']['family'] {
'Debian': {
$service_name = 'ssh'
}
'RedHat', 'Suse': { # several values
$service_name = 'sshd'
}
/^(?i:windows)$/: { # a regular expression
$service_name = 'sshd'
}
default: {
fail('unsupported')
}
}
service { $service_name:
ensure => running,
enable => true,
}
case can also match data types:
puppet
case $value {
Integer: { notice('a number') }
String[1]: { notice('a non-empty string') }
Array[String]: { notice('an array of strings') }
default: { notice('something else') }
}
Selectors: Choose a Value
A selector is an expression that returns a value. It is perfect for choosing one setting based on a condition.
puppet
$package_name = $facts['os']['family'] ? {
'Debian' => 'apache2',
'RedHat' => 'httpd',
default => 'apache',
}
file { '/etc/hostname':
ensure => file,
mode => $facts['kernel'] ? { 'Linux' => '0644', default => undef },
}
Choose by readability: Use a selector to pick one value. Use case or if when you need to run several statements or declare resources.
Better Approach: Data in Hiera
Large case blocks for every operating system make code long. The cleaner pattern is to keep OS differences in Hiera data (a later lesson). Conditionals are best for logic, not for big tables of values.
Iteration with Lambdas
A lambda is a small block of code |$parameter| { ... } passed to an iteration function. Puppet has no for loop. You use functions like each instead.
each: do something for every item
puppet
$users = ['alice', 'bob', 'carol']
$users.each |$name| {
user { $name:
ensure => present,
managehome => true,
}
}
# Same with index
$users.each |$index, $name| {
notice("${index}: ${name}")
}
each over a hash
puppet
$sites = {
'shop.example.com' => { 'port' => 8080, 'ssl' => true },
'blog.example.com' => { 'port' => 8081, 'ssl' => false },
}
$sites.each |$host, $cfg| {
file { "/etc/nginx/conf.d/${host}.conf":
ensure => file,
content => epp('profile/vhost.conf.epp', {
'server_name' => $host,
'port' => $cfg['port'],
'ssl' => $cfg['ssl'],
}),
notify => Service['nginx'],
}
}
map, filter, reduce and others
puppet
$nums = [1, 2, 3, 4, 5, 6]
$doubled = $nums.map |$n| { $n * 2 } # [2, 4, 6, 8, 10, 12]
$evens = $nums.filter |$n| { $n % 2 == 0 } # [2, 4, 6]
$sum = $nums.reduce |$memo, $n| { $memo + $n } # 21
$names = ['web1', 'web2'].map |$h| { "${h}.example.com" }
# Hash helpers
$ports = { 'web' => 80, 'tls' => 443 }
$bigger = $ports.filter |$k, $v| { $v > 100 } # { 'tls' => 443 }
$flipped = $ports.map |$k, $v| { [$v, $k] } # array of pairs
$total = $ports.values.reduce |$a, $b| { $a + $b }
| Function | What it does |
each | Run code for every element, returns the original |
map | Transform each element into a new array |
filter | Keep elements where the block is true |
reduce | Combine all elements into one value |
slice | Process in chunks |
with | Call a block once with given values (create a local scope) |
unique, flatten, sort, reverse_each | Utility helpers |
Creating Resources from Data
This is a very common pattern: data in a hash, resources created by a loop. The result is easy to extend: add a new entry, get a new resource.
puppet
$accounts = {
'alice' => { 'uid' => 2001, 'groups' => ['sudo', 'developers'], 'shell' => '/bin/bash' },
'bob' => { 'uid' => 2002, 'groups' => ['developers'], 'shell' => '/bin/zsh' },
}
$accounts.each |$login, $info| {
user { $login:
ensure => present,
uid => $info['uid'],
groups => $info['groups'],
shell => $info['shell'],
managehome => true,
}
}
The built-in function create_resources($type, $hash) does something similar, but lambdas are clearer and more flexible.
Resource Expressions with Splat and Defaults
puppet
$file_defaults = { 'owner' => 'root', 'group' => 'root', 'mode' => '0644' }
file { '/etc/a.conf':
ensure => file,
* => $file_defaults, # splat: expand a hash into attributes
}
Handling Missing Data Safely
puppet
$level = $facts.dig('custom', 'tier') ? { # dig avoids errors if keys are missing
undef => 'standard',
default => $facts['custom']['tier'],
}
$port = pick($override_port, $default_port, 80) # first non-empty value (from stdlib)
Readable Code Guidelines
- Keep conditionals shallow. Move complex logic into functions or classes
- Prefer data (Hiera) for values and code for behaviour
- Always provide a
default branch, and use fail() with a clear message for unsupported systems
- Prefer
$facts['os']['family'] to detailed version checks unless needed
- Run
puppet-lint (a later lesson) to keep style consistent
Practice Tasks
- Write a manifest that chooses the Apache package and service name with a
case statement
- Use a selector to set
/etc/ssh/sshd_config permissions differently on Linux and Windows
- Create five directories
/opt/app1 to /opt/app5 using each and a range or array
- Build a hash of users and create them with a lambda
- Use
filter to select only the ports above 1024 from an array
Conclusion
Use if, case and selectors to adapt to the node, and use each, map and filter with lambdas to turn data into resources. Keep logic small and move data to Hiera.
Quick Summary: 0 and '' are true; case/selector for OS; each/map/filter/reduce; resources from hashes; splat *.