Conditional statements and expressions
Conditional statements let your Puppet code behave differently in different situations. They are most helpful when combined with facts or with data retrieved from an external source. Puppet supports if and unless statements, case statements, and selectors.
Examples
An if
statement evaluates the given
condition and, if the condition resolves to true
, executes the given code.
This example includes an elsif
condition, and gives a warning if you try to
include the ntp
class on a virtual machine or on machine running macOS:
if $facts['is_virtual'] { warning('Tried to include class ntp on virtual machine; this node might be misclassified.') } elsif $facts['os']['family'] == 'Darwin' { warning('This NTP module does not yet work on our Mac laptops.') } else { include ntp }
An
unless
statement takes a Boolean condition and an arbitrary block of Puppet code, evaluates the condition, and if the condition is
false, execute the code block. This statement sets $maxclient
to 500 unless
the system memory is above the specified
parameter.
unless $facts['memory']['system']['totalbytes'] > 1073741824 { $maxclient = 500 }
A case statement evaluates a list of cases against a control expression, and executes the first code block where the case value matches the control expression. This example declares a role class on a node, but which role class it declares depends on what operating system the node runs:
case $facts['os']['name'] { 'RedHat', 'CentOS': { include role::redhat } /^(Debian|Ubuntu)$/: { include role::debian } default: { include role::generic } }
A selector statement is similar to a case statement, but instead of executing code, it returns a value. This example returns the value 'wheel' for the specified operating systems, but the value 'root' for all other operating systems:
$rootgroup = $facts['os']['family'] ? { 'RedHat' => 'wheel', /(Debian|Ubuntu)/ => 'wheel', default => 'root', } file { '/etc/passwd': ensure => file, owner => 'root', group => $rootgroup, }