unless statements

"Unless" statements work like reversed if statements. They take a Boolean condition and an arbitrary block of Puppet code, evaluate the condition, and if it is false, execute the code block. They cannot include elsif clauses.

Behavior

The condition is evaluated first and, if it is false, the code block is executed. If the condition is true, Puppet does nothing and moves on.

In addition to executing the code in a block, an unless statement is also an expression that produces a value, and it can be used wherever a value is allowed. The value of an unless expression is the value of the last expression in the executed block. If no block was executed, the value is undef.

Syntax

The general form of an unless statement is:

  • The unless keyword.

  • A condition (any expression resolving to a Boolean value).

  • A pair of curly braces containing any Puppet code.

  • Optionally: the else keyword and a pair of curly braces containing Puppet code.

You cannot include an elsif clause in an unless statement. If you do, compilation fails with a syntax error.
unless $facts['memory']['system']['totalbytes'] > 1073741824 {
  $maxclient = 500
}

Conditions

The condition of an unless statement can be any expression that resolves to a Boolean value. This includes:

Expressions that resolve to non-Boolean values are automatically converted to Booleans. For more information, see the Booleans documentation.

Regex capture variables

Although unless statements receive regex capture variables like if statements, you wouldn't usually use one, because the code in the statement is executed only if the condition doesn't match anything. It generally makes more sense to use an if statement.