Conditionals
Puppet provides different constructs to manage conditionals inside manifests.
Selectors as we have seen, let us set the value of a variable or an argument inside a resource declaration according to the value of another variable. Selectors, therefore, just return values, and are not used to manage conditionally entire blocks of code.
Here's an example of a selector:
$package_name = $::osfamily ? { 'RedHat' => 'httpd', 'Debian' => 'apache2', default => undef, }
The case
statements are used to execute different blocks of code according to the values of a variable. It's recommended to have a default block for unmatched entries. Case statements can't be used inside resource declarations. We can achieve the same result of the previous selector with this case
sample:
case $::osfamily { 'Debian': { $package_name = 'apache2' } 'RedHat': { $package_name = 'httpd' } default: { fail ("Operating system $::operatingsystem not supported") } }
The if
, elsif
, and else
conditionals, like case
, are used to execute different blocks of code and can't be used inside resources declarations. We can use any of Puppet's comparison expressions and we can combine more than one for complex patterns matching.
The previous sample variables assignment can also be expressed in this way:
if $::osfamily == 'Debian' { $package_name = 'apache2' } elsif $::osfamily == 'RedHat' { $package_name = 'httpd' } else { fail ("Operating system $::operatingsystem not supported") }
The unless
condition is the opposite of if
. It evaluates a Boolean condition and, if it's false, it executes a block of code. The use of unless
instead of negating the if
condition is more a personal preference, but it shouldn't be used with complex expressions as it reduces readability.