Adding control structures in manifests
You have written three simple manifests while following the instructions in this chapter so far. Each comprised only one resource, and one of them was given on the command line using the -e
option. Of course, you would not want to write distinct manifests for each possible circumstance. Instead, just as how Ruby or Perl scripts branch out into different code paths, there are structures that make your Puppet code flexible and reusable for different circumstances.
The most common control element is the if
/else
block. It is quite similar to its equivalents in many programming languages:
if 'mail_lda' in $needed_services { service { 'dovecot': enable => true } } else { service { 'dovecot': enable => false } }
The Puppet DSL also has a case
statement, which is reminiscent of its counterparts in other languages as well:
case $role { 'imap_server': { package { 'dovecot': ensure => 'installed' } service { 'dovecot': ensure => 'running' } } /_webserver$/: { service { [ 'apache', 'ssh' ]: ensure => 'running' } } default: { service { 'ssh': ensure => running } } }
A variation of the case
statement is the selector. It's an expression, not a statement, and can be used in a fashion similar to the ternary if
/else
operator found in C-like languages:
package { 'dovecot': ensure => $role ? { 'imap_server' => 'installed', /desktop$/ => 'purged', default => 'removed', }, }
It should be used with caution, because in more complex manifests, this syntax will impede readability.