Selector expressions
Selector expressions are similar to case statements, but instead of executing code, they return a value.
Behavior
The entire selector expression is treated as a single value.Puppet compares the control expression to each of the cases, in
the order they are listed (except for the default
case,
which always goes last). When it finds a matching case, it treats that value as the value of
the expression and ignore the remainder of the expression. If none of the cases match, Puppet fails compilation with an error, unless a default
case is also provided.
The control expression of a selector can be any expression that resolves to a value. This includes:
Functions that return values
Selectors can be used wherever a value is expected. This includes:
Variable assignments
Resource attributes
Function arguments
Resource titles
A value in another selector
Expressions
Syntax
Selectors resemble a cross between a case statement and the ternary operator found in other languages. The general form of a selector is:
-
A control expression, which is any expression resolving to a value.
-
The
?
(question mark) keyword. -
An opening curly brace.
-
Any number of possible matches, each of which consists of:
-
A case.
-
The
=>
(hash rocket) keyword. -
A value, which can be any expression resolving to a value.
-
A trailing comma.
-
- A closing curly brace.
In this example, the value of $rootgroup
is determined using the
value of $facts['os']['family']
:
$rootgroup = $facts['os']['family'] ? { 'Redhat' => 'wheel', /(Debian|Ubuntu)/ => 'wheel', default => 'root', } file { '/etc/passwd': ensure => file, owner => 'root', group => $rootgroup, }
Case matching
In selector statements, you cannot use lists of cases. If the control expression is a string and you need more than one case associated with a single value, use a regular expression. Otherwise, use a case statement instead of a selector, because case statements do allow lists of cases. For more information, see Case statements.
Regex capture variables
If you use regular expression cases, any captures
from parentheses in the pattern are available inside the associated value as numbered
variables ($1
, $2
), and the entire match is
available as $0
:
puppet $system = $facts['os']['name'] ? { /(RedHat|Debian)/ => "our system is ${1}", default => "our system is unknown", }
Regex capture variables are different from other variables in a couple of ways:
-
The values of the numbered variables do not persist outside the value associated with the pattern that set them.
-
In nested conditionals, each conditional has its own set of values for the set of numbered variables. At the end of an interior statement, the numbered variables are reset to their previous values for the remainder of the outside statement. This causes conditional statements to act like local scopes, but only with regard to the numbered variables.