Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 38 ยท Manifests and Resources

Conditionals and Operators

Write platform-aware Puppet code with if, unless, case and selector expressions, comparison, boolean, in and regex operators, and avoid the classic truthiness traps.

Real servers differ: Debian uses apache2, Red Hat uses httpd; small machines get a smaller cache. Conditionals let one piece of code adapt to the node it is compiled for. Because the decision happens on the server at compile time, the agent receives a catalog that already has the right choice baked in.

if, elsif, else

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 }

Braces are mandatory and there are no parentheses around the condition. The fail() function stops the compile with a clear message: a good default branch for unsupported platforms, since silently doing nothing hides problems. Variables assigned inside an if block are visible after it in the same scope.

unless is the negated form (no elsif, else is allowed but discouraged):

PUPPET
unless $facts['virtual'] == 'physical' {
  notice('This node is a virtual machine')
}

case

case compares one value against several options:

PUPPET
case $facts['os']['name'] {
  'Ubuntu', 'Debian': { $pkg = 'apache2' }
  'CentOS', 'RedHat', 'Rocky': { $pkg = 'httpd' }
  /^Windows/: { $pkg = 'iis' }
  default: { fail('unsupported OS') }
}

Options may be strings, regular expressions, data types (Integer[1, 9]:) or comma-separated alternatives. The first match wins. Always include default.

Selector expressions

A selector is an expression that returns a value, handy for assigning one variable:

PUPPET
$service = $facts['os']['family'] ? {
  'Debian' => 'apache2',
  'RedHat' => 'httpd',
  default  => 'httpd',
}

Selectors can sit inside a resource declaration, which is where they are most common:

PUPPET
file { '/etc/app.conf':
  mode => $facts['os']['family'] ? {
    'windows' => undef,
    default   => '0644',
  },
}

A selector with no matching case and no default is a compile error.

Comparison, boolean and other operators

Operator Meaning Example
==, != equal, not equal (strings are case-insensitive) $a == 'Web' matches 'web'
<, >, <=, >= numeric comparison $cores >= 4
and, or, ! boolean logic $a and !$b
in membership in string, array, hash keys 'git' in $packages
=~, !~ regex or type match $host =~ /^web\d+$/
+ - * / % arithmetic $mem / 1024
<<, >> shift (or array append with <<) $list << 'x'
+ on arrays/hashes concatenation / merge $a + $b

Two gotchas deserve attention.

  • String equality ignores case. 'Debian' == 'debian' is true. For exact comparison, match with a regex or compare lowercased values deliberately.
  • Truthiness. Only false and undef are false. A string 'false' or 0 is true. When data comes from Hiera, make sure booleans are real booleans (YAML false, not "false"); typing the parameter as Boolean catches this.

Regex match captures are available as $0, $1, ... inside the matched block:

PUPPET
if $facts['networking']['hostname'] =~ /^(web|app)(\d+)$/ {
  $role   = $1            # 'web'
  $number = $2            # '1'
}

Putting it together

A common real-world shape is a small "params" block that translates facts into settings, then declares resources from those settings:

PUPPET
$settings = $facts['os']['family'] ? {
  'Debian' => { 'package' => 'apache2', 'service' => 'apache2', 'confdir' => '/etc/apache2' },
  'RedHat' => { 'package' => 'httpd',   'service' => 'httpd',   'confdir' => '/etc/httpd/conf.d' },
  default  => fail('unsupported'),
}

package { $settings['package']: ensure => installed }
service { $settings['service']: ensure => running, enable => true }

In a module this logic is usually moved into Hiera data per operating system (Hiera), which keeps the class free of if trees.

A stand-in: case, selector and truthiness

Python Stand-in: pick a package per platform

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Stand-in: Puppet truthiness and string equality

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The stand-in's first loop shows exactly where Puppet and Python disagree: 0, "" and [] are true in Puppet.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a selector expression do?

    A selector evaluates to the value of the first matching case.
  2. 2. Which string is truthy in Puppet?

    Any non-empty string, even 'false', is truthy; only boolean false and undef are falsy.
  3. 3. What does 'Debian' == 'debian' return?

    String equality in Puppet is case-insensitive.
  4. 4. What should a case statement on OS name normally end with?

    A default branch handles unexpected values explicitly.

Summary

  • if/elsif/else, unless, case and selectors choose behaviour at compile time.
  • Always add a default branch; use fail() for unsupported platforms.
  • String == is case-insensitive; only false and undef are falsy.
  • in, =~ and arithmetic operators work as shown in the table.
  • Move platform differences into Hiera data when logic grows.

Next: Resource Relationships and Ordering