Function Reference

This version is not included in Puppet Enterprise.

This page is autogenerated; any changes will get overwritten (last generated on 2016-09-22 14:44:52 -0700)

There are two types of functions in Puppet: Statements and rvalues. Statements stand on their own and do not return arguments; they are used for performing stand-alone work like importing. Rvalues return values and can only be used in a statement requiring a value, such as an assignment or a case statement.

Functions execute on the Puppet master. They do not execute on the Puppet agent. Hence they only have access to the commands and data available on the Puppet master host.

Here are the functions available in Puppet:

alert

Log a message on the server at level alert.

  • Type: statement

assert_type

Returns the given value if it is of the given data type, or otherwise either raises an error or executes an optional two-parameter lambda.

The function takes two mandatory arguments, in this order:

  1. The expected data type.
  2. A value to compare against the expected data type.

Example: Using assert_type

$raw_username = 'Amy Berry'

# Assert that $raw_username is a non-empty string and assign it to $valid_username.
$valid_username = assert_type(String[1], $raw_username)

# $valid_username contains "Amy Berry".
# If $raw_username was an empty string or a different data type, the Puppet run would
# fail with an "Expected type does not match actual" error.

You can use an optional lambda to provide enhanced feedback. The lambda takes two mandatory parameters, in this order:

  1. The expected data type as described in the function’s first argument.
  2. The actual data type of the value.

Example: Using assert_type with a warning and default value

$raw_username = 'Amy Berry'

# Assert that $raw_username is a non-empty string and assign it to $valid_username.
# If it isn't, output a warning describing the problem and use a default value.
$valid_username = assert_type(String[1], $raw_username) |$expected, $actual| {
  warning( "The username should be '${expected}', not '${actual}'. Using 'anonymous'." )
  'anonymous'
}

# $valid_username contains "Amy Berry".
# If $raw_username was an empty string, the Puppet run would set $valid_username to
# "anonymous" and output a warning: "The username should be 'String[1, default]', not
# 'String[0, 0]'. Using 'anonymous'."

For more information about data types, see the documentation.

  • Since 4.0.0

  • Type: rvalue

contain

Contain one or more classes inside the current class. If any of these classes are undeclared, they will be declared as if called with the include function. Accepts a class name, an array of class names, or a comma-separated list of class names.

A contained class will not be applied before the containing class is begun, and will be finished before the containing class is finished.

You must use the class’s full name; relative names are not allowed. In addition to names in string form, you may also directly use Class and Resource Type values that are produced by evaluating resource and relationship expressions.

  • Since 4.0.0 support for Class and Resource Type values, absolute names

  • Type: statement

create_resources

Converts a hash into a set of resources and adds them to the catalog.

This function takes two mandatory arguments: a resource type, and a hash describing a set of resources. The hash should be in the form {title => {parameters} }:

# A hash of user resources:
$myusers = {
  'nick' => { uid    => '1330',
              gid    => allstaff,
              groups => ['developers', 'operations', 'release'], },
  'dan'  => { uid    => '1308',
              gid    => allstaff,
              groups => ['developers', 'prosvc', 'release'], },
}

create_resources(user, $myusers)

A third, optional parameter may be given, also as a hash:

$defaults = {
  'ensure'   => present,
  'provider' => 'ldap',
}

create_resources(user, $myusers, $defaults)

The values given on the third argument are added to the parameters of each resource present in the set given on the second argument. If a parameter is present on both the second and third arguments, the one on the second argument takes precedence.

This function can be used to create defined resources and classes, as well as native resources.

Virtual and Exported resources may be created by prefixing the type name with @ or @@ respectively. For example, the $myusers hash may be exported in the following manner:

create_resources("@@user", $myusers)

The $myusers may be declared as virtual resources using:

create_resources("@user", $myusers)

Note that create_resources will filter out parameter values that are undef so that normal data binding and puppet default value expressions are considered (in that order) for the final value of a parameter (just as when setting a parameter to undef in a puppet language resource declaration).

  • Type: statement

crit

Log a message on the server at level crit.

  • Type: statement

debug

Log a message on the server at level debug.

  • Type: statement

defined

Determines whether a given class or resource type is defined and returns a Boolean value. You can also use defined to determine whether a specific resource is defined, or whether a variable has a value (including undef, as opposed to the variable never being declared or assigned).

This function takes at least one string argument, which can be a class name, type name, resource reference, or variable reference of the form '$name'.

The defined function checks both native and defined types, including types provided by modules. Types and classes are matched by their names. The function matches resource declarations by using resource references.

Examples: Different types of defined function matches

# Matching resource types
defined("file")
defined("customtype")

# Matching defines and classes
defined("foo")
defined("foo::bar")

# Matching variables
defined('$name')

# Matching declared resources
defined(File['/tmp/file'])

Puppet depends on the configuration’s evaluation order when checking whether a resource is declared.

Example: Importance of evaluation order when using defined

# Assign values to $is_defined_before and $is_defined_after using identical `defined`
# functions.

$is_defined_before = defined(File['/tmp/file'])

file { "/tmp/file":
  ensure => present,
}

$is_defined_after = defined(File['/tmp/file'])

# $is_defined_before returns false, but $is_defined_after returns true.

This order requirement only refers to evaluation order. The order of resources in the configuration graph (e.g. with before or require) does not affect the defined function’s behavior.

Warning: Avoid relying on the result of the defined function in modules, as you might not be able to guarantee the evaluation order well enough to produce consistent results. This can cause other code that relies on the function’s result to behave inconsistently or fail.

If you pass more than one argument to defined, the function returns true if any of the arguments are defined. You can also match resources by type, allowing you to match conditions of different levels of specificity, such as whether a specific resource is of a specific data type.

Example: Matching multiple resources and resources by different types with defined

file { "/tmp/file1":
  ensure => file,
}

$tmp_file = file { "/tmp/file2":
  ensure => file,
}

# Each of these statements return `true` ...
defined(File['/tmp/file1'])
defined(File['/tmp/file1'],File['/tmp/file2'])
defined(File['/tmp/file1'],File['/tmp/file2'],File['/tmp/file3'])
# ... but this returns `false`.
defined(File['/tmp/file3'])

# Each of these statements returns `true` ...
defined(Type[Resource['file','/tmp/file2']])
defined(Resource['file','/tmp/file2'])
defined(File['/tmp/file2'])
defined('$tmp_file')
# ... but each of these returns `false`.
defined(Type[Resource['exec','/tmp/file2']])
defined(Resource['exec','/tmp/file2'])
defined(File['/tmp/file3'])
defined('$tmp_file2')
  • Since 2.7.0
  • Since 3.6.0 variable reference and future parser types
  • Since 3.8.1 type specific requests with future parser
  • Since 4.0.0 includes all future parser features

  • Type: rvalue

dig

Returns a value for a sequence of given keys/indexes into a structure. This function is used to “dig into” a complex data structure by using a sequence of keys / indexes to access a value from which the next key/index is accessed recursively.

The first encountered undef value or key stops the “dig” and undef is returned.

An error is raised if an attempt is made to “dig” into something other than an undef (which immediately returns undef), an Array or a Hash.

Example: Using dig

$data = {a => { b => [{x => 10, y => 20}, {x => 100, y => 200}]}}
notice $data.dig(a, b, 1, x)

Would notice the value 100.

  • Since 4.5.0

  • Type: rvalue

digest

Returns a hash value from a provided string using the digest_algorithm setting from the Puppet config file.

  • Type: rvalue

each

Runs a lambda repeatedly using each value in a data structure, then returns the values unchanged.

This function takes two mandatory arguments, in this order:

  1. An array or hash the function will iterate over.
  2. A lambda, which the function calls for each element in the first argument. It can request one or two parameters.

Example: Using the each function

$data.each |$parameter| { <PUPPET CODE BLOCK> }

or

each($data) |$parameter| { <PUPPET CODE BLOCK> }

When the first argument ($data in the above example) is an array, Puppet passes each value in turn to the lambda, then returns the original values.

Example: Using the each function with an array and a one-parameter lambda

# For the array $data, run a lambda that creates a resource for each item.
$data = ["routers", "servers", "workstations"]
$data.each |$item| {
 notify { $item:
   message => $item
 }
}
# Puppet creates one resource for each of the three items in $data. Each resource is
# named after the item's value and uses the item's value in a parameter.

When the first argument is a hash, Puppet passes each key and value pair to the lambda as an array in the form [key, value] and returns the original hash.

Example: Using the each function with a hash and a one-parameter lambda

# For the hash $data, run a lambda using each item as a key-value array that creates a
# resource for each item.
$data = {"rtr" => "Router", "svr" => "Server", "wks" => "Workstation"}
$data.each |$items| {
 notify { $items[0]:
   message => $items[1]
 }
}
# Puppet creates one resource for each of the three items in $data, each named after the
# item's key and containing a parameter using the item's value.

When the first argument is an array and the lambda has two parameters, Puppet passes the array’s indexes (enumerated from 0) in the first parameter and its values in the second parameter.

Example: Using the each function with an array and a two-parameter lambda

# For the array $data, run a lambda using each item's index and value that creates a
# resource for each item.
$data = ["routers", "servers", "workstations"]
$data.each |$index, $value| {
 notify { $value:
   message => $index
 }
}
# Puppet creates one resource for each of the three items in $data, each named after the
# item's value and containing a parameter using the item's index.

When the first argument is a hash, Puppet passes its keys to the first parameter and its values to the second parameter.

Example: Using the each function with a hash and a two-parameter lambda

# For the hash $data, run a lambda using each item's key and value to create a resource
# for each item.
$data = {"rtr" => "Router", "svr" => "Server", "wks" => "Workstation"}
$data.each |$key, $value| {
 notify { $key:
   message => $value
 }
}
# Puppet creates one resource for each of the three items in $data, each named after the
# item's key and containing a parameter using the item's value.

For an example that demonstrates how to create multiple file resources using each, see the Puppet iteration documentation.

  • Since 4.0.0

  • Type: rvalue

emerg

Log a message on the server at level emerg.

  • Type: statement

epp

Evaluates an Embedded Puppet (EPP) template file and returns the rendered text result as a String.

epp('<MODULE NAME>/<TEMPLATE FILE>', <PARAMETER HASH>)

The first argument to this function should be a <MODULE NAME>/<TEMPLATE FILE> reference, which loads <TEMPLATE FILE> from <MODULE NAME>’s templates directory. In most cases, the last argument is optional; if used, it should be a hash that contains parameters to pass to the template.

  • See the template documentation for general template usage information.
  • See the EPP syntax documentation for examples of EPP.

For example, to call the apache module’s templates/vhost/_docroot.epp template and pass the docroot and virtual_docroot parameters, call the epp function like this:

epp('apache/templates/vhost/_docroot.epp', { 'docroot' => '/var/www/html', 'virtual_docroot' => '/var/www/example' })

Puppet produces a syntax error if you pass more parameters than are declared in the template’s parameter tag. When passing parameters to a template that contains a parameter tag, use the same names as the tag’s declared parameters.

Parameters are required only if they are declared in the called template’s parameter tag without default values. Puppet produces an error if the epp function fails to pass any required parameter.

  • Since 4.0.0

  • Type: rvalue

err

Log a message on the server at level err.

  • Type: statement

fail

Fail with a parse error.

  • Type: statement

file

Loads a file from a module and returns its contents as a string.

The argument to this function should be a <MODULE NAME>/<FILE> reference, which will load <FILE> from a module’s files directory. (For example, the reference mysql/mysqltuner.pl will load the file <MODULES DIRECTORY>/mysql/files/mysqltuner.pl.)

This function can also accept:

  • An absolute path, which can load a file from anywhere on disk.
  • Multiple arguments, which will return the contents of the first file found, skipping any files that don’t exist.

  • Type: rvalue

filter

Applies a lambda to every value in a data structure and returns an array or hash containing any elements for which the lambda evaluates to true.

This function takes two mandatory arguments, in this order:

  1. An array or hash the function will iterate over.
  2. A lambda, which the function calls for each element in the first argument. It can request one or two parameters.

Example: Using the filter function

$filtered_data = $data.filter |$parameter| { <PUPPET CODE BLOCK> }

or

$filtered_data = filter($data) |$parameter| { <PUPPET CODE BLOCK> }

When the first argument ($data in the above example) is an array, Puppet passes each value in turn to the lambda and returns an array containing the results.

Example: Using the filter function with an array and a one-parameter lambda

# For the array $data, return an array containing the values that end with "berry"
$data = ["orange", "blueberry", "raspberry"]
$filtered_data = $data.filter |$items| { $items =~ /berry$/ }
# $filtered_data = [blueberry, raspberry]

When the first argument is a hash, Puppet passes each key and value pair to the lambda as an array in the form [key, value] and returns a hash containing the results.

Example: Using the filter function with a hash and a one-parameter lambda

# For the hash $data, return a hash containing all values of keys that end with "berry"
$data = { "orange" => 0, "blueberry" => 1, "raspberry" => 2 }
$filtered_data = $data.filter |$items| { $items[0] =~ /berry$/ }
# $filtered_data = {blueberry => 1, raspberry => 2}

When the first argument is an array and the lambda has two parameters, Puppet passes the
array's indexes (enumerated from 0) in the first parameter and its values in the second
parameter.

**Example**: Using the `filter` function with an array and a two-parameter lambda

~~~ puppet
# For the array $data, return an array of all keys that both end with "berry" and have
# an even-numbered index
$data = ["orange", "blueberry", "raspberry"]
$filtered_data = $data.filter |$indexes, $values| { $indexes % 2 == 0 and $values =~ /berry$/ }
# $filtered_data = [raspberry]

When the first argument is a hash, Puppet passes its keys to the first parameter and its values to the second parameter.

Example: Using the filter function with a hash and a two-parameter lambda

# For the hash $data, return a hash of all keys that both end with "berry" and have
# values less than or equal to 1
$data = { "orange" => 0, "blueberry" => 1, "raspberry" => 2 }
$filtered_data = $data.filter |$keys, $values| { $keys =~ /berry$/ and $values <= 1 }
# $filtered_data = {blueberry => 1}
  • Since 4.0.0

  • Type: rvalue

fqdn_rand

Usage: fqdn_rand(MAX, [SEED]). MAX is required and must be a positive integer; SEED is optional and may be any number or string.

Generates a random Integer number greater than or equal to 0 and less than MAX, combining the $fqdn fact and the value of SEED for repeatable randomness. (That is, each node will get a different random number from this function, but a given node’s result will be the same every time unless its hostname changes.)

This function is usually used for spacing out runs of resource-intensive cron tasks that run on many nodes, which could cause a thundering herd or degrade other services if they all fire at once. Adding a SEED can be useful when you have more than one such task and need several unrelated random numbers per node. (For example, fqdn_rand(30), fqdn_rand(30, 'expensive job 1'), and fqdn_rand(30, 'expensive job 2') will produce totally different numbers.)

  • Type: rvalue

generate

Calls an external command on the Puppet master and returns the results of the command. Any arguments are passed to the external command as arguments. If the generator does not exit with return code of 0, the generator is considered to have failed and a parse error is thrown. Generators can only have file separators, alphanumerics, dashes, and periods in them. This function will attempt to protect you from malicious generator calls (e.g., those with ‘..’ in them), but it can never be entirely safe. No subshell is used to execute generators, so all shell metacharacters are passed directly to the generator.

  • Type: rvalue

hiera

Performs a standard priority lookup of the hierarchy and returns the most specific value for a given key. The returned value can be any type of data.

The function takes up to three arguments, in this order:

  1. A string key that Hiera searches for in the hierarchy. Required.
  2. An optional default value to return if Hiera doesn’t find anything matching the key.
    • If this argument isn’t provided and this function results in a lookup failure, Puppet fails with a compilation error.
  3. The optional name of an arbitrary hierarchy level to insert at the top of the hierarchy. This lets you temporarily modify the hierarchy for a single lookup.
    • If Hiera doesn’t find a matching key in the overriding hierarchy level, it continues searching the rest of the hierarchy.

The hiera function does not find all matches throughout a hierarchy, instead returining the first specific value starting at the top of the hierarchy. To search throughout a hierarchy, use the hiera_array or hiera_hash functions.

Example: Using hiera

# Assuming hiera.yaml
# :hierarchy:
#   - web01.example.com
#   - common

# Assuming web01.example.com.yaml:
# users:
#   - "Amy Barry"
#   - "Carrie Douglas"

# Assuming common.yaml:
users:
  admins:
    - "Edith Franklin"
    - "Ginny Hamilton"
  regular:
    - "Iris Jackson"
    - "Kelly Lambert"
# Assuming we are not web01.example.com:

$users = hiera('users', undef)

# $users contains {admins  => ["Edith Franklin", "Ginny Hamilton"],
#                  regular => ["Iris Jackson", "Kelly Lambert"]}

You can optionally generate the default value with a lambda that takes one parameter.

Example: Using hiera with a lambda

# Assuming the same Hiera data as the previous example:

$users = hiera('users') | $key | { "Key '${key}' not found" }

# $users contains {admins  => ["Edith Franklin", "Ginny Hamilton"],
#                  regular => ["Iris Jackson", "Kelly Lambert"]}
# If hiera couldn't match its key, it would return the lambda result,
# "Key 'users' not found".

The returned value’s data type depends on the types of the results. In the example above, Hiera matches the ‘users’ key and returns it as a hash.

See the documentation for more information about Hiera lookup functions.

  • Since 4.0.0

  • Type: rvalue

hiera_array

Finds all matches of a key throughout the hierarchy and returns them as a single flattened array of unique values. If any of the matched values are arrays, they’re flattened and included in the results. This is called an array merge lookup.

The hiera_array function takes up to three arguments, in this order:

  1. A string key that Hiera searches for in the hierarchy. Required.
  2. An optional default value to return if Hiera doesn’t find anything matching the key.
    • If this argument isn’t provided and this function results in a lookup failure, Puppet fails with a compilation error.
  3. The optional name of an arbitrary hierarchy level to insert at the top of the hierarchy. This lets you temporarily modify the hierarchy for a single lookup.
    • If Hiera doesn’t find a matching key in the overriding hierarchy level, it continues searching the rest of the hierarchy.

Example: Using hiera_array

# Assuming hiera.yaml
# :hierarchy:
#   - web01.example.com
#   - common

# Assuming common.yaml:
# users:
#   - 'cdouglas = regular'
#   - 'efranklin = regular'

# Assuming web01.example.com.yaml:
# users: 'abarry = admin'
$allusers = hiera_array('users', undef)

# $allusers contains ["cdouglas = regular", "efranklin = regular", "abarry = admin"].

You can optionally generate the default value with a lambda that takes one parameter.

Example: Using hiera_array with a lambda

# Assuming the same Hiera data as the previous example:

$allusers = hiera_array('users') | $key | { "Key '${key}' not found" }

# $allusers contains ["cdouglas = regular", "efranklin = regular", "abarry = admin"].
# If hiera_array couldn't match its key, it would return the lambda result,
# "Key 'users' not found".

hiera_array expects that all values returned will be strings or arrays. If any matched value is a hash, Puppet raises a type mismatch error.

See the documentation for more information about Hiera lookup functions.

  • Since 4.0.0

  • Type: rvalue

hiera_hash

Finds all matches of a key throughout the hierarchy and returns them in a merged hash. If any of the matched hashes share keys, the final hash uses the value from the highest priority match. This is called a hash merge lookup.

The merge strategy is determined by Hiera’s :merge_behavior setting.

The hiera_hash function takes up to three arguments, in this order:

  1. A string key that Hiera searches for in the hierarchy. Required.
  2. An optional default value to return if Hiera doesn’t find anything matching the key.
    • If this argument isn’t provided and this function results in a lookup failure, Puppet fails with a compilation error.
  3. The optional name of an arbitrary hierarchy level to insert at the top of the hierarchy. This lets you temporarily modify the hierarchy for a single lookup.
    • If Hiera doesn’t find a matching key in the overriding hierarchy level, it continues searching the rest of the hierarchy.

Example: Using hiera_hash

# Assuming hiera.yaml
# :hierarchy:
#   - web01.example.com
#   - common

# Assuming common.yaml:
# users:
#   regular:
#     'cdouglas': 'Carrie Douglas'

# Assuming web01.example.com.yaml:
# users:
#   administrators:
#     'aberry': 'Amy Berry'
# Assuming we are not web01.example.com:

$allusers = hiera_hash('users', undef)

# $allusers contains {regular => {"cdouglas" => "Carrie Douglas"},
#                     administrators => {"aberry" => "Amy Berry"}}

You can optionally generate the default value with a lambda that takes one parameter.

Example: Using hiera_hash with a lambda

# Assuming the same Hiera data as the previous example:

$allusers = hiera_hash('users') | $key | { "Key '${key}' not found" }

# $allusers contains {regular => {"cdouglas" => "Carrie Douglas"},
#                     administrators => {"aberry" => "Amy Berry"}}
# If hiera_hash couldn't match its key, it would return the lambda result,
# "Key 'users' not found".

hiera_hash expects that all values returned will be hashes. If any of the values found in the data sources are strings or arrays, Puppet raises a type mismatch error.

See the documentation for more information about Hiera lookup functions.

  • Since 4.0.0

  • Type: rvalue

hiera_include

Assigns classes to a node using an array merge lookup that retrieves the value for a user-specified key from Hiera’s data.

The hiera_include function requires:

  • A string key name to use for classes.
  • A call to this function (i.e. hiera_include('classes')) in your environment’s sites.pp manifest, outside of any node definitions and below any top-scope variables that Hiera uses in lookups.
  • classes keys in the appropriate Hiera data sources, with an array for each classes key and each value of the array containing the name of a class.

The function takes up to three arguments, in this order:

  1. A string key that Hiera searches for in the hierarchy. Required.
  2. An optional default value to return if Hiera doesn’t find anything matching the key.
    • If this argument isn’t provided and this function results in a lookup failure, Puppet fails with a compilation error.
  3. The optional name of an arbitrary hierarchy level to insert at the top of the hierarchy. This lets you temporarily modify the hierarchy for a single lookup.
    • If Hiera doesn’t find a matching key in the overriding hierarchy level, it continues searching the rest of the hierarchy.

The function uses an array merge lookup to retrieve the classes array, so every node gets every class from the hierarchy.

Example: Using hiera_include

# Assuming hiera.yaml
# :hierarchy:
#   - web01.example.com
#   - common

# Assuming web01.example.com.yaml:
# classes:
#   - apache::mod::php

# Assuming common.yaml:
# classes:
#   - apache
# In site.pp, outside of any node definitions and below any top-scope variables:
hiera_include('classes', undef)

# Puppet assigns the apache and apache::mod::php classes to the web01.example.com node.

You can optionally generate the default value with a lambda that takes one parameter.

Example: Using hiera_include with a lambda

# Assuming the same Hiera data as the previous example:

# In site.pp, outside of any node definitions and below any top-scope variables:
hiera_include('classes') | $key | {"Key '${key}' not found" }

# Puppet assigns the apache and apache::mod::php classes to the web01.example.com node.
# If hiera_include couldn't match its key, it would return the lambda result,
# "Key 'classes' not found".

See the documentation for more information and a more detailed example of how hiera_include uses array merge lookups to classify nodes.

  • Since 4.0.0

  • Type: statement

include

Declares one or more classes, causing the resources in them to be evaluated and added to the catalog. Accepts a class name, an array of class names, or a comma-separated list of class names.

The include function can be used multiple times on the same class and will only declare a given class once. If a class declared with include has any parameters, Puppet will automatically look up values for them in Hiera, using <class name>::<parameter name> as the lookup key.

Contrast this behavior with resource-like class declarations (class {'name': parameter => 'value',}), which must be used in only one place per class and can directly set parameters. You should avoid using both include and resource-like declarations with the same class.

The include function does not cause classes to be contained in the class where they are declared. For that, see the contain function. It also does not create a dependency relationship between the declared class and the surrounding class; for that, see the require function.

You must use the class’s full name; relative names are not allowed. In addition to names in string form, you may also directly use Class and Resource Type values that are produced by the future parser’s resource and relationship expressions.

  • Since < 3.0.0
  • Since 4.0.0 support for class and resource type values, absolute names

  • Type: statement

info

Log a message on the server at level info.

  • Type: statement

inline_epp

Evaluates an Embedded Puppet (EPP) template string and returns the rendered text result as a String.

inline_epp('<EPP TEMPLATE STRING>', <PARAMETER HASH>)

The first argument to this function should be a string containing an EPP template. In most cases, the last argument is optional; if used, it should be a hash that contains parameters to pass to the template.

  • See the template documentation for general template usage information.
  • See the EPP syntax documentation for examples of EPP.

For example, to evaluate an inline EPP template and pass it the docroot and virtual_docroot parameters, call the inline_epp function like this:

inline_epp('docroot: <%= $docroot %> Virtual docroot: <%= $virtual_docroot %>', { 'docroot' => '/var/www/html', 'virtual_docroot' => '/var/www/example' })

Puppet produces a syntax error if you pass more parameters than are declared in the template’s parameter tag. When passing parameters to a template that contains a parameter tag, use the same names as the tag’s declared parameters.

Parameters are required only if they are declared in the called template’s parameter tag without default values. Puppet produces an error if the inline_epp function fails to pass any required parameter.

An inline EPP template should be written as a single-quoted string or heredoc. A double-quoted string is subject to expression interpolation before the string is parsed as an EPP template.

For example, to evaluate an inline EPP template using a heredoc, call the inline_epp function like this:

# Outputs 'Hello given argument planet!'
inline_epp(@(END), { x => 'given argument' })
<%- | $x, $y = planet | -%>
Hello <%= $x %> <%= $y %>!
END
  • Since 3.5
  • Requires future parser in Puppet 3.5 to 3.8

  • Type: rvalue

inline_template

Evaluate a template string and return its value. See the templating docs for more information. Note that if multiple template strings are specified, their output is all concatenated and returned as the output of the function.

  • Type: rvalue

lest

Call a lambda with the given argument unless the argument is undef. Return undef if argument is undef, and otherwise the result of giving the argument to the lambda.

This is useful to process a sequence of operations where an intermediate result may be undef (which makes the entire sequence undef). The then function is especially useful with the function dig which performs in a similar way “digging out” a value in a complex structure.

Example: Using dig and then

$data = {a => { b => [{x => 10, y => 20}, {x => 100, y => 200}]}}
notice $data.dig(a, b, 1, x).then |$x| { $x * 2 }

Would notice the value 200

Contrast this with:

$data = {a => { b => [{x => 10, y => 20}, {ex => 100, why => 200}]}}
notice $data.dig(a, b, 1, x).then |$x| { $x * 2 }

Which would notice undef since the last lookup of ‘x’ results in undef which is returned (without calling the lambda given to the then function).

As a result there is no need for conditional logic or a temporary (non local) variable as the result is now either the wanted value (x) multiplied by 2 or undef.

Calls to then can be chained. In the next example, a structure is using an offset based on using 1 as the index to the first element (instead of 0 which is used in the language). We are not sure if user input actually contains an index at all, or if it is outside the range of available names.args.

Example: Chaining calls to the then function

# Names to choose from
$names = ['Ringo', 'Paul', 'George', 'John']

# Structure where 'beatle 2' is wanted (but where the number refers
# to 'Paul' because input comes from a source using 1 for the first
# element).

$data = ['singer', { beatle => 2 }]
$picked = assert_type(String,
  # the data we are interested in is the second in the array,
  # a hash, where we want the value of the key 'beatle'
  $data.dig(1, 'beatle')
    # and we want the index in $names before the given index
    .then |$x| { $names[$x-1] }
    # so we can construct a string with that beatle's name
    .then |$x| { "Picked Beatle '${x}'" }
)

Would notice “Picked Beatle ‘Paul’”, and would raise an error if the result was not a String.

  • Since 4.5.0

  • Type: rvalue

lookup

Uses the Puppet lookup system to retrieve a value for a given key. By default, this returns the first value found (and fails compilation if no values are available), but you can configure it to merge multiple values into one, fail gracefully, and more.

When looking up a key, Puppet will search up to three tiers of data, in the following order:

  1. Hiera.
  2. The current environment’s data provider.
  3. The indicated module’s data provider, if the key is of the form <MODULE NAME>::<SOMETHING>.

Arguments

You must provide the name of a key to look up, and can optionally provide other arguments. You can combine these arguments in the following ways:

  • lookup( <NAME>, [<VALUE TYPE>], [<MERGE BEHAVIOR>], [<DEFAULT VALUE>] )
  • lookup( [<NAME>], <OPTIONS HASH> )
  • lookup( as above ) |$key| { # lambda returns a default value }

Arguments in [square brackets] are optional.

The arguments accepted by lookup are as follows:

  1. <NAME> (string or array) — The name of the key to look up.
    • This can also be an array of keys. If Puppet doesn’t find anything for the first key, it will try again with the subsequent ones, only resorting to a default value if none of them succeed.
  2. <VALUE TYPE> (data type) — A data type that must match the retrieved value; if not, the lookup (and catalog compilation) will fail. Defaults to Data (accepts any normal value).
  3. <MERGE BEHAVIOR> (string or hash; see “Merge Behaviors” below) — Whether (and how) to combine multiple values. If present, this overrides any merge behavior specified in the data sources. Defaults to no value; Puppet will use merge behavior from the data sources if present, and will otherwise do a first-found lookup.
  4. <DEFAULT VALUE> (any normal value) — If present, lookup returns this when it can’t find a normal value. Default values are never merged with found values. Like a normal value, the default must match the value type. Defaults to no value; if Puppet can’t find a normal value, the lookup (and compilation) will fail.
  5. <OPTIONS HASH> (hash) — Alternate way to set the arguments above, plus some less-common extra options. If you pass an options hash, you can’t combine it with any regular arguments (except <NAME>). An options hash can have the following keys:
    • 'name' — Same as <NAME> (argument 1). You can pass this as an argument or in the hash, but not both.
    • 'value_type' — Same as <VALUE TYPE> (argument 2).
    • 'merge' — Same as <MERGE BEHAVIOR> (argument 3).
    • 'default_value' — Same as <DEFAULT VALUE> (argument 4).
    • 'default_values_hash' (hash) — A hash of lookup keys and default values. If Puppet can’t find a normal value, it will check this hash for the requested key before giving up. You can combine this with default_value or a lambda, which will be used if the key isn’t present in this hash. Defaults to an empty hash.
    • 'override' (hash) — A hash of lookup keys and override values. Puppet will check for the requested key in the overrides hash first; if found, it returns that value as the final value, ignoring merge behavior. Defaults to an empty hash.

Finally, lookup can take a lambda, which must accept a single parameter. This is yet another way to set a default value for the lookup; if no results are found, Puppet will pass the requested key to the lambda and use its result as the default value.

Merge Behaviors

Puppet lookup uses a hierarchy of data sources, and a given key might have values in multiple sources. By default, Puppet returns the first value it finds, but it can also continue searching and merge all the values together.

Note: Data sources can use the special lookup_options metadata key to request a specific merge behavior for a key. The lookup function will use that requested behavior unless you explicitly specify one.

The valid merge behaviors are:

  • 'first' — Returns the first value found, with no merging. Puppet lookup’s default behavior.
  • 'unique' (called “array merge” in classic Hiera) — Combines any number of arrays and scalar values to return a merged, flattened array with all duplicate values removed. The lookup will fail if any hash values are found.
  • 'hash' — Combines the keys and values of any number of hashes to return a merged hash. If the same key exists in multiple source hashes, Puppet will use the value from the highest-priority data source; it won’t recursively merge the values.
  • 'deep' — Combines the keys and values of any number of hashes to return a merged hash. If the same key exists in multiple source hashes, Puppet will recursively merge hash or array values (with duplicate values removed from arrays). For conflicting scalar values, the highest-priority value will win.
  • {'strategy' => 'first|unique|hash'} — Same as the string versions of these merge behaviors.
  • {'strategy' => 'deep', <DEEP OPTION> => <VALUE>, ...} — Same as 'deep', but can adjust the merge with additional options. The available options are:
    • 'knockout_prefix' (string or undef) — A string prefix to indicate a value should be removed from the final result. Defaults to undef, which disables this feature.
    • 'sort_merged_arrays' (boolean) — Whether to sort all arrays that are merged together. Defaults to false.
    • 'merge_hash_arrays' (boolean) — Whether to merge hashes within arrays. Defaults to false.

Examples

Look up a key and return the first value found:

lookup('ntp::service_name')

Do a unique merge lookup of class names, then add all of those classes to the catalog (like hiera_include):

lookup('classes', Array[String], 'unique').include

Do a deep hash merge lookup of user data, but let higher priority sources remove values by prefixing them with --:

lookup( { 'name'  => 'users',
          'merge' => {
            'strategy'        => 'deep',
            'knockout_prefix' => '--',
          },
})
  • Type: rvalue

map

Applies a lambda to every value in a data structure and returns an array containing the results.

This function takes two mandatory arguments, in this order:

  1. An array or hash the function will iterate over.
  2. A lambda, which the function calls for each element in the first argument. It can request one or two parameters.

Example: Using the map function

$transformed_data = $data.map |$parameter| { <PUPPET CODE BLOCK> }

or

$transformed_data = map($data) |$parameter| { <PUPPET CODE BLOCK> }

When the first argument ($data in the above example) is an array, Puppet passes each value in turn to the lambda.

Example: Using the map function with an array and a one-parameter lambda

# For the array $data, return an array containing each value multiplied by 10
$data = [1,2,3]
$transformed_data = $data.map |$items| { $items * 10 }
# $transformed_data contains [10,20,30]

When the first argument is a hash, Puppet passes each key and value pair to the lambda as an array in the form [key, value].

Example: Using the map function with a hash and a one-parameter lambda

# For the hash $data, return an array containing the keys
$data = {'a'=>1,'b'=>2,'c'=>3}
$transformed_data = $data.map |$items| { $items[0] }
# $transformed_data contains ['a','b','c']

When the first argument is an array and the lambda has two parameters, Puppet passes the array’s indexes (enumerated from 0) in the first parameter and its values in the second parameter.

Example: Using the map function with an array and a two-parameter lambda

# For the array $data, return an array containing the indexes
$data = [1,2,3]
$transformed_data = $data.map |$index,$value| { $index }
# $transformed_data contains [0,1,2]

When the first argument is a hash, Puppet passes its keys to the first parameter and its values to the second parameter.

Example: Using the map function with a hash and a two-parameter lambda

# For the hash $data, return an array containing each value
$data = {'a'=>1,'b'=>2,'c'=>3}
$transformed_data = $data.map |$key,$value| { $value }
# $transformed_data contains [1,2,3]
  • Since 4.0.0

  • Type: rvalue

match

Matches a regular expression against a string and returns an array containing the match and any matched capturing groups.

The first argument is a string or array of strings. The second argument is either a regular expression, regular expression represented as a string, or Regex or Pattern data type that the function matches against the first argument.

The returned array contains the entire match at index 0, and each captured group at subsequent index values. If the value or expression being matched is an array, the function returns an array with mapped match results.

If the function doesn’t find a match, it returns ‘undef’.

Example: Matching a regular expression in a string

$matches = "abc123".match(/[a-z]+[1-9]+/)
# $matches contains [abc123]

Example: Matching a regular expressions with grouping captures in a string

$matches = "abc123".match(/([a-z]+)([1-9]+)/)
# $matches contains [abc123, abc, 123]

Example: Matching a regular expression with grouping captures in an array of strings

$matches = ["abc123","def456"].match(/([a-z]+)([1-9]+)/)
# $matches contains [[abc123, abc, 123], [def456, def, 456]]
  • Since 4.0.0

  • Type: statement

md5

Returns a MD5 hash value from a provided string.

  • Type: rvalue

new

Creates a new instance/object of a given data type.

This function makes it possible to create new instances of concrete data types. If a block is given it is called with the just created instance as an argument.

Calling this function is equivalent to directly calling the data type:

Example: new and calling type directly are equivalent

$a = Integer.new("42")
$b = Integer("42")

These would both convert the string "42" to the decimal value 42.

Example: arguments by position or by name

$a = Integer.new("42", 8)
$b = Integer({from => "42", radix => 8})

This would convert the octal (radix 8) number "42" in string form to the decimal value 34.

The new function supports two ways of giving the arguments:

  • by name (using a hash with property to value mapping)
  • by position (as regular arguments)

Note that it is not possible to create new instances of some abstract data types (for example Variant). The data type Optional[T] is an exception as it will create an instance of T or undef if the value to convert is undef.

The arguments that can be given is determined by the data type.

An assertion is always made that the produced value complies with the given type constraints.

Example: data type constraints are checked

Integer[0].new("-100")

Would fail with an assertion error (since value is less than 0).

The following sections show the arguments and conversion rules per data type built into the Puppet Type System.

Conversion to Optional[T] and NotUndef[T]

Conversion to these data types is the same as a conversion to the type argument T. In the case of Optional[T] it is accepted that the argument to convert may be undef. It is however not acceptable to give other arguments (than undef) that cannot be converted to T.

Conversion to Integer

A new Integer can be created from Integer, Float, Boolean, and String values. For conversion from String it is possible to specify the radix (base).

type Radix = Variant[Default, Integer[2,2], Integer[8,8], Integer[10,10], Integer[16,16]]

function Integer.new(
  String $value,
  Radix $radix = 10
)

function Integer.new(
  Variant[Numeric, Boolean] $value
)
  • When converting from String the default radix is 10.
  • If radix is not specified an attempt is made to detect the radix from the start of the string:
    • 0b or 0B is taken as radix 2.
    • 0x or 0X is taken as radix 16.
    • 0 as radix 8.
    • All others are decimal.
  • Conversion from String accepts an optional sign in the string.
  • For hexadecimal (radix 16) conversion an optional leading “0x”, or “0X” is accepted.
  • For octal (radix 8) an optional leading “0” is accepted.
  • For binary (radix 2) an optional leading “0b” or “0B” is accepted.
  • When radix is set to default, the conversion is based on the leading. characters in the string. A leading “0” for radix 8, a leading “0x”, or “0X” for radix 16, and leading “0b” or “0B” for binary.
  • Conversion from Boolean results in 0 for false and 1 for true.
  • Conversion from Integer, Float, and Boolean ignores the radix.
  • Float value fractions are truncated (no rounding).

Examples - Converting to Integer:

$a_number = Integer("0xFF", 16)  # results in 255
$a_number = Numeric("010")       # results in 8
$a_number = Numeric("010", 10)   # results in 10
$a_number = Integer(true)        # results in 1

Conversion to Float

A new Float can be created from Integer, Float, Boolean, and String values. For conversion from String both float and integer formats are supported.

function Float.new(
  Variant[Numeric, Boolean, String] $value
)
  • For an integer, the floating point fraction of .0 is added to the value.
  • A Boolean true is converted to 1.0, and a false to 0.0
  • In String format, integer prefixes for hex and binary are understood (but not octal since floating point in string format may start with a ‘0’).

Conversion to Numeric

A new Integer or Float can be created from Integer, Float, Boolean and String values.

function Numeric.new(
  Variant[Numeric, Boolean, String] $value
)
  • If the value has a decimal period, or if given in scientific notation (e/E), the result is a Float, otherwise the value is an Integer. The conversion from String always uses a radix based on the prefix of the string.
  • Conversion from Boolean results in 0 for false and 1 for true.

Examples - Converting to Numeric

$a_number = Numeric(true)    # results in 1
$a_number = Numeric("0xFF")  # results in 255
$a_number = Numeric("010")   # results in 8
$a_number = Numeric("3.14")  # results in 3.14 (a float)

Conversion to String

Conversion to String is the most comprehensive conversion as there are many use cases where a string representation is wanted. The defaults for the many options have been chosen with care to be the most basic “value in textual form” representation. The more advanced forms of formatting are intended to enable writing special purposes formatting functions in the Puppet language.

A new string can be created from all other data types. The process is performed in several steps - first the data type of the given value is inferred, then the resulting data type is used to find the most significant format specified for that data type. And finally, the found format is used to convert the given value.

The mapping from data type to format is referred to as the format map. This map allows different formatting depending on type.

Example: Positive Integers in Hexadecimal prefixed with ‘0x’, negative in Decimal

$format_map = {
  Integer[default, 0] => "%d",
  Integer[1, default] => "%#x"
}
String("-1", $format_map)  # produces '-1'
String("10", $format_map)  # produces '0xa'

A format is specified on the form:

%[Flags][Width][.Precision]Format

Width is the number of characters into which the value should be fitted. This allocated space is padded if value is shorter. By default it is space padded, and the flag 0 will cause padding with 0 for numerical formats.

Precision is the number of fractional digits to show for floating point, and the maximum characters included in a string format.

Note that all data type supports the formats s and p with the meaning “default string representation” and “default programmatic string representation” (which for example means that a String is quoted in ‘p’ format).

Signatures of String conversion

type Format = Pattern[/^%([ +-#0[{<(|]*)([1-9][0-9]*)?(?:.([0-9]+))?([a-zA-Z])/]
type ContainerFormat = Struct[{
  format         => Optional[String],
  separator      => Optional[String],
  separator2     => Optional[String],
  string_formats => Hash[Type, Format]
  }]
type TypeMap = Hash[Type, Variant[Format, ContainerFormat]]
type Formats = Variant[Default, String[1], TypeMap]

function String.new(
  Any $value,
  Formats $string_formats
)

Where:

  • separator is the string used to separate entries in an array, or hash (extra space should not be included at the end), defaults to ","
  • separator2 is the separator between key and value in a hash entry (space padding should be included as wanted), defaults to " => ".
  • string_formats is a data type to format map for values contained in arrays and hashes - defaults to {Any => "%p"}. Note that these nested formats are not applicable to data types that are containers; they are always formatted as per the top level format specification.

Example: Simple Conversion to String (using defaults)

$str = String(10)      # produces '10'
$str = String([10])    # produces '["10"]'

Example: Simple Conversion to String specifying the format for the given value directly

$str = String(10, "%#x")    # produces '0x10'
$str = String([10], "%(a")  # produces '("10")'

Example: Specifying type for values contained in an array

$formats = {
  Array => {
    format => '%(a',
    string_formats => { Integer => '%#x' }
  }
}
$str = String([1,2,3], $formats) # produces '(0x1, 0x2, 0x3)'

The given formats are merged with the default formats, and matching of values to convert against format is based on the specificity of the mapped type; for example, different formats can be used for short and long arrays.

Integer to String

Format Integer Formats
d Decimal, negative values produces leading ‘-‘.
x X Hexadecimal in lower or upper case. Uses ..f/..F for negative values unless + is also used. A # adds prefix 0x/0X.
o Octal. Uses ..0 for negative values unless + is also used. A # adds prefix 0.
b B Binary with prefix ‘b’ or ‘B’. Uses ..1/..1 for negative values unless + is also used.
c Numeric value representing a Unicode value, result is a one unicode character string, quoted if alternative flag # is used
s Same as d, or d in quotes if alternative flag # is used.
p Same as d.
eEfgGaA Converts integer to float and formats using the floating point rules.

Defaults to d.

Float to String

Format Float formats
f Floating point in non exponential notation.
e E Exponential notation with ‘e’ or ‘E’.
g G Conditional exponential with ‘e’ or ‘E’ if exponent < -4 or >= the precision.
a A Hexadecimal exponential form, using ‘x’/’X’ as prefix and ‘p’/’P’ before exponent.
s Converted to string using format p, then applying string formatting rule, alternate form # quotes result.
p Same as f format with minimum significant number of fractional digits, prec has no effect.
dxXobBc Converts float to integer and formats using the integer rules.

Defaults to p.

String to String

Format String
s Unquoted string, verbatim output of control chars.
p Programmatic representation - strings are quoted, interior quotes and control chars are escaped.
C Each :: name segment capitalized, quoted if alternative flag # is used.
c Capitalized string, quoted if alternative flag # is used.
d Downcased string, quoted if alternative flag # is used.
u Upcased string, quoted if alternative flag # is used.
t Trims leading and trailing whitespace from the string, quoted if alternative flag # is used.

Defaults to s at top level and p inside array or hash.

Boolean to String

Format Boolean Formats
t T String ‘true’/’false’ or ‘True’/’False’, first char if alternate form is used (i.e. ‘t’/’f’ or ‘T’/’F’).
y Y String ‘yes’/’no’, ‘Yes’/’No’, ‘y’/’n’ or ‘Y’/’N’ if alternative flag # is used.
dxXobB Numeric value 0/1 in accordance with the given format which must be valid integer format.
eEfgGaA Numeric value 0.0/1.0 in accordance with the given float format and flags.
s String ‘true’ / ‘false’.
p String ‘true’ / ‘false’.

Regexp to String

Format Regexp Formats
s Delimiters / /, alternate flag # replaces / delimiters with quotes.
p Delimiters / /.

Undef to String

Format Undef formats
s Empty string, or quoted empty string if alternative flag # is used.
p String ‘undef’, or quoted ‘“undef”’ if alternative flag # is used.
n String ‘nil’, or ‘null’ if alternative flag # is used.
dxXobB String ‘NaN’.
eEfgGaA String ‘NaN’.
v String ‘n/a’.
V String ‘N/A’.
u String ‘undef’, or ‘undefined’ if alternative # flag is used.

Default value to String

Format Default formats
d D String ‘default’ or ‘Default’, alternative form # causes value to be quoted.
s Same as d.
p Same as d.

Array & Tuple to String

Format Array/Tuple Formats
a Formats with [ ] delimiters and ,, alternate form # indents nested arrays/hashes.
s Same as a.
p Same as a.

See “Flags” <[({| for formatting of delimiters, and “Additional parameters for containers; Array and Hash” for more information about options.

The alternate form flag # will cause indentation of nested array or hash containers. If width is also set it is taken as the maximum allowed length of a sequence of elements (not including delimiters). If this max length is exceeded, each element will be indented.

Hash & Struct to String

Format Hash/Struct Formats
h Formats with { } delimiters, , element separator and ` => ` inner element separator unless overridden by flags.
s Same as h.
p Same as h.
a Converts the hash to an array of [k,v] tuples and formats it using array rule(s).

See “Flags” <[({| for formatting of delimiters, and “Additional parameters for containers; Array and Hash” for more information about options.

The alternate form flag # will format each hash key/value entry indented on a separate line.

Type to String

Format Array/Tuple Formats
s The same as p, quoted if alternative flag # is used.
p Outputs the type in string form as specified by the Puppet Language.

Flags

Flag Effect      
(space) A space instead of + for numeric output (- is shown), for containers skips delimiters.      
# Alternate format; prefix 0x/0x, 0 (octal) and 0b/0B for binary, Floats force decimal ‘.’. For g/G keep trailing 0.      
+ Show sign +/- depending on value’s sign, changes x, X, o, b, B format to not use 2’s complement form.      
- Left justify the value in the given width.      
0 Pad with 0 instead of space for widths larger than value.      
<[({   Defines an enclosing pair <> [] () {} or   when used with a container type.

Conversion to Boolean

Accepts a single value as argument:

  • Float 0.0 is false, all other float values are true
  • Integer 0 is false, all other integer values are true
  • Strings
    • true if ‘true’, ‘yes’, ‘y’ (case independent compare)
    • false if ‘false’, ‘no’, ‘n’ (case independent compare)
  • Boolean is already boolean and is simply returned

Conversion to Array and Tuple

When given a single value as argument:

  • A non empty Hash is converted to an array matching Array[Tuple[Any,Any], 1].
  • An empty Hash becomes an empty array.
  • An Array is simply returned.
  • An Iterable[T] is turned into an array of T instances.

When given a second Boolean argument:

  • if true, a value that is not already an array is returned as a one element array.
  • if false, (the default), converts the first argument as shown above.

Example: Ensuring value is an array

$arr = Array($value, true)

Conversion to a Tuple works exactly as conversion to an Array, only that the constructed array is asserted against the given tuple type.

Conversion to Hash and Struct

Accepts a single value as argument:

  • An empty Array becomes an empty Hash
  • An Array matching Array[Tuple[Any,Any], 1] is converted to a hash where each tuple describes a key/value entry
  • An Array with an even number of entries is interpreted as [key1, val1, key2, val2, ...]
  • An Iterable is turned into an Array and then converted to hash as per the array rules
  • A Hash is simply returned

Conversion to a Struct works exactly as conversion to a Hash, only that the constructed hash is asserted against the given struct type.

Creating a SemVer

A SemVer object represents a single Semantic Version. It can be created from a String, individual values for its parts, or a hash specifying the value per part. See the specification at semver.org for the meaning of the SemVer’s parts.

The signatures are:

type PositiveInteger = Integer[0,default]
type SemVerQualifier = Pattern[/A(?<part>[0-9A-Za-z-]+)(?:.g<part>)*Z/]
type SemVerString = String[1]
type SemVerHash =Struct[{
  major                => PositiveInteger,
  minor                => PositiveInteger,
  patch                => PositiveInteger,
  Optional[prerelease] => SemVerQualifier,
  Optional[build]      => SemVerQualifier
}]

function SemVer.new(SemVerString $str)

function SemVer.new(
        PositiveInteger           $major
        PositiveInteger           $minor
        PositiveInteger           $patch
        Optional[SemVerQualifier] $prerelease = undef
        Optional[SemVerQualifier] $build = undef
        )

function SemVer.new(SemVerHash $hash_args)

Examples: SemVer and SemVerRange usage

# As a type, SemVer can describe disjunct ranges which versions can be
# matched against - here the type is constructed with two
# SemVerRange objects.
#
$t = SemVer[
  SemVerRange('>=1.0.0 <2.0.0'),
  SemVerRange('>=3.0.0 <4.0.0')
]
notice(SemVer('1.2.3') =~ $t) # true
notice(SemVer('2.3.4') =~ $t) # false
notice(SemVer('3.4.5') =~ $t) # true

Creating a SemVerRange

A SemVerRange object represents a range of SemVer. It can be created from a String, or from two SemVer instances, where either end can be given as a literal default to indicate infinity. The string format of a SemVerRange is specified by the Semantic Version Range Grammar.

Use of the comparator sets described in the grammar (joining with ||) is not supported.

The signatures are:

type SemVerRangeString = String[1]
type SemVerRangeHash = Struct[{
  min                   => Variant[default, SemVer],
  Optional[max]         => Variant[default, SemVer],
  Optional[exclude_max] => Boolean
}]

function SemVerRange.new(
  SemVerRangeString $semver_range_string
)

function SemVerRange.new(
  Variant[default,SemVer] $min
  Variant[default,SemVer] $max
  Optional[Boolean]       $exclude_max = undef
)

function SemVerRange.new(
  SemVerRangeHash $semver_range_hash
)

For examples of SemVerRange use see “Creating a SemVer”

  • Since 4.5.0

  • Type: rvalue

notice

Log a message on the server at level notice.

  • Type: statement

realize

Make a virtual object real. This is useful when you want to know the name of the virtual object and don’t want to bother with a full collection. It is slightly faster than a collection, and, of course, is a bit shorter. You must pass the object using a reference; e.g.: realize User[luke].

  • Type: statement

reduce

Applies a lambda to every value in a data structure from the first argument, carrying over the returned value of each iteration, and returns the result of the lambda’s final iteration. This lets you create a new value or data structure by combining values from the first argument’s data structure.

This function takes two mandatory arguments, in this order:

  1. An array or hash the function will iterate over.
  2. A lambda, which the function calls for each element in the first argument. It takes two mandatory parameters:
    1. A memo value that is overwritten after each iteration with the iteration’s result.
    2. A second value that is overwritten after each iteration with the next value in the function’s first argument.

Example: Using the reduce function

$data.reduce |$memo, $value| { ... }

or

reduce($data) |$memo, $value| { ... }

You can also pass an optional “start memo” value as an argument, such as start below:

$data.reduce(start) |$memo, $value| { ... }

or

reduce($data, start) |$memo, $value| { ... }

When the first argument ($data in the above example) is an array, Puppet passes each of the data structure’s values in turn to the lambda’s parameters. When the first argument is a hash, Puppet converts each of the hash’s values to an array in the form [key, value].

If you pass a start memo value, Puppet executes the lambda with the provided memo value and the data structure’s first value. Otherwise, Puppet passes the structure’s first two values to the lambda.

Puppet calls the lambda for each of the data structure’s remaining values. For each call, it passes the result of the previous call as the first parameter ($memo in the above examples) and the next value from the data structure as the second parameter ($value).

If the structure has one value, Puppet returns the value and does not call the lambda.

Example: Using the reduce function

# Reduce the array $data, returning the sum of all values in the array.
$data = [1, 2, 3]
$sum = $data.reduce |$memo, $value| { $memo + $value }
# $sum contains 6

# Reduce the array $data, returning the sum of a start memo value and all values in the
# array.
$data = [1, 2, 3]
$sum = $data.reduce(4) |$memo, $value| { $memo + $value }
# $sum contains 10

# Reduce the hash $data, returning the sum of all values and concatenated string of all
# keys.
$data = {a => 1, b => 2, c => 3}
$combine = $data.reduce |$memo, $value| {
  $string = "${memo[0]}${value[0]}"
  $number = $memo[1] + $value[1]
  [$string, $number]
}
# $combine contains [abc, 6]

Example: Using the reduce function with a start memo and two-parameter lambda

# Reduce the array $data, returning the sum of all values in the array and starting
# with $memo set to an arbitrary value instead of $data's first value.
$data = [1, 2, 3]
$sum = $data.reduce(4) |$memo, $value| { $memo + $value }
# At the start of the lambda's first iteration, $memo contains 4 and $value contains 1.
# After all iterations, $sum contains 10.

# Reduce the hash $data, returning the sum of all values and concatenated string of
# all keys, and starting with $memo set to an arbitrary array instead of $data's first
# key-value pair.
$data = {a => 1, b => 2, c => 3}
$combine = $data.reduce( [d, 4] ) |$memo, $value| {
  $string = "${memo[0]}${value[0]}"
  $number = $memo[1] + $value[1]
  [$string, $number]
}
# At the start of the lambda's first iteration, $memo contains [d, 4] and $value
# contains [a, 1].
# $combine contains [dabc, 10]
  • Since 4.0.0

  • Type: rvalue

regsubst

Perform regexp replacement on a string or array of strings.

  • Parameters (in order):
    • target The string or array of strings to operate on. If an array, the replacement will be performed on each of the elements in the array, and the return value will be an array.
    • regexp The regular expression matching the target string. If you want it anchored at the start and or end of the string, you must do that with ^ and $ yourself.
    • replacement Replacement string. Can contain backreferences to what was matched using \0 (whole match), \1 (first set of parentheses), and so on.
    • flags Optional. String of single letter flags for how the regexp is interpreted:
      • E Extended regexps
      • I Ignore case in regexps
      • M Multiline regexps
      • G Global replacement; all occurrences of the regexp in each target string will be replaced. Without this, only the first occurrence will be replaced.
    • encoding Optional. How to handle multibyte characters. A single-character string with the following values:
      • N None
      • E EUC
      • S SJIS
      • U UTF-8
  • Examples

Get the third octet from the node’s IP address:

$i3 = regsubst($ipaddress,'^(\d+)\.(\d+)\.(\d+)\.(\d+)$','\3')

Put angle brackets around each octet in the node’s IP address:

$x = regsubst($ipaddress, '([0-9]+)', '<\1>', 'G')
  • Type: rvalue

require

Evaluate one or more classes, adding the required class as a dependency.

The relationship metaparameters work well for specifying relationships between individual resources, but they can be clumsy for specifying relationships between classes. This function is a superset of the ‘include’ function, adding a class relationship so that the requiring class depends on the required class.

Warning: using require in place of include can lead to unwanted dependency cycles.

For instance the following manifest, with ‘require’ instead of ‘include’ would produce a nasty dependence cycle, because notify imposes a before between File[/foo] and Service[foo]:

class myservice {
  service { foo: ensure => running }
}

class otherstuff {
  include myservice
  file { '/foo': notify => Service[foo] }
}

Note that this function only works with clients 0.25 and later, and it will fail if used with earlier clients.

You must use the class’s full name; relative names are not allowed. In addition to names in string form, you may also directly use Class and Resource Type values that are produced when evaluating resource and relationship expressions.

  • Since 4.0.0 Class and Resource types, absolute names

  • Type: statement

reverse_each

Reverses the order of the elements of something that is iterable and optionally runs a lambda for each element.

This function takes one to two arguments:

  1. An Iterable that the function will iterate over.
  2. An optional lambda, which the function calls for each element in the first argument. It must request one parameter.

Example: Using the reverse_each function

$data.reverse_each |$parameter| { <PUPPET CODE BLOCK> }

or

$reverse_data = $data.reverse_each

or

reverse_each($data) |$parameter| { <PUPPET CODE BLOCK> }

or

$reverse_data = reverse_each($data)

When no second argument is present, Puppet returns an Iterable that represents the reverse order of its first argument. This allows methods on Iterable to be chained.

When a lamdba is given as the second argument, Puppet iterates the first argument in reverse order and passes each value in turn to the lambda, then returns undef.

Example: Using the reverse_each function with an array and a one-parameter lambda

# Puppet will log a notice for each of the three items
# in $data in reverse order.
$data = [1,2,3]
$data.reverse_each |$item| { notice($item) }

When no second argument is present, Puppet returns a new Iterable which allows it to be directly chained into another function that takes an Iterable as an argument.

Example: Using the reverse_each function chained with a map function.

# For the array $data, return an array containing each
# value multiplied by 10 in reverse order
$data = [1,2,3]
$transformed_data = $data.reverse_each.map |$item| { $item * 10 }
# $transformed_data is set to [30,20,10]

Example: Using reverse_each function chained with a map in alternative syntax

# For the array $data, return an array containing each
# value multiplied by 10 in reverse order
$data = [1,2,3]
$transformed_data = map(reverse_each($data)) |$item| { $item * 10 }
# $transformed_data is set to [30,20,10]
  • Since 4.4.0

  • Type: rvalue

scanf

Scans a string and returns an array of one or more converted values based on the given format string. See the documentation of Ruby’s String#scanf method for details about the supported formats (which are similar but not identical to the formats used in Puppet’s sprintf function.)

This function takes two mandatory arguments: the first is the string to convert, and the second is the format string. The result of the scan is an array, with each successfully scanned and transformed value. The scanning stops if a scan is unsuccessful, and the scanned result up to that point is returned. If there was no successful scan, the result is an empty array.

“42”.scanf(“%i”)

You can also optionally pass a lambda to scanf, to do additional validation or processing.

"42".scanf("%i") |$x| {
  unless $x[0] =~ Integer {
    fail "Expected a well formed integer value, got '$x[0]'"
  }
  $x[0]
} - since 4.0.0
  • Type: rvalue

sha1

Returns a SHA1 hash value from a provided string.

  • Type: rvalue

shellquote

Quote and concatenate arguments for use in Bourne shell.

Each argument is quoted separately, and then all are concatenated with spaces. If an argument is an array, the elements of that array is interpolated within the rest of the arguments; this makes it possible to have an array of arguments and pass that array to shellquote instead of having to specify each argument individually in the call.

  • Type: rvalue

slice

This function takes two mandatory arguments: the first should be an array or hash, and the second specifies the number of elements to include in each slice.

When the first argument is a hash, each key value pair is counted as one. For example, a slice size of 2 will produce an array of two arrays with key, and value.

$a.slice(2) |$entry|          { notice "first ${$entry[0]}, second ${$entry[1]}" }
$a.slice(2) |$first, $second| { notice "first ${first}, second ${second}" }

The function produces a concatenated result of the slices.

slice([1,2,3,4,5,6], 2) # produces [[1,2], [3,4], [5,6]]
slice(Integer[1,6], 2)  # produces [[1,2], [3,4], [5,6]]
slice(4,2)              # produces [[0,1], [2,3]]
slice('hello',2)        # produces [[h, e], [l, l], [o]]

You can also optionally pass a lambda to slice.

$a.slice($n) |$x| { ... }
slice($a) |$x| { ... }

The lambda should have either one parameter (receiving an array with the slice), or the same number of parameters as specified by the slice size (each parameter receiving its part of the slice). If there are fewer remaining elements than the slice size for the last slice, it will contain the remaining elements. If the lambda has multiple parameters, excess parameters are set to undef for an array, or to empty arrays for a hash.

$a.slice(2) |$first, $second| { ... }
  • Since 4.0.0

  • Type: rvalue

split

Split a string variable into an array using the specified split regexp.

Example:

$string     = 'v1.v2:v3.v4'
$array_var1 = split($string, ':')
$array_var2 = split($string, '[.]')
$array_var3 = split($string, Regexp['[.:]'])

$array_var1 now holds the result ['v1.v2', 'v3.v4'], while $array_var2 holds ['v1', 'v2:v3', 'v4'], and $array_var3 holds ['v1', 'v2', 'v3', 'v4'].

Note that in the second example, we split on a literal string that contains a regexp meta-character (.), which must be escaped. A simple way to do that for a single character is to enclose it in square brackets; a backslash will also escape a single character.

  • Type: rvalue

sprintf

Perform printf-style formatting of text.

The first parameter is format string describing how the rest of the parameters should be formatted. See the documentation for the Kernel::sprintf function in Ruby for all the details.

  • Type: rvalue

step

Provides stepping with given interval over elements in an iterable and optionally runs a lambda for each element.

This function takes two to three arguments:

  1. An ‘Iterable’ that the function will iterate over.
  2. An Integer step factor. This must be a positive integer.
  3. An optional lambda, which the function calls for each element in the interval. It must request one parameter.

Example: Using the step function

$data.step(<n>) |$parameter| { <PUPPET CODE BLOCK> }

or

$stepped_data = $data.step(<n>)

or

step($data, <n>) |$parameter| { <PUPPET CODE BLOCK> }

or

$stepped_data = step($data, <n>)

When no block is given, Puppet returns an Iterable that yields the first element and every nth successor element, from its first argument. This allows functions on iterables to be chained. When a block is given, Puppet iterates and calls the block with the first element and then with every nth successor element. It then returns undef.

Example: Using the step function with an array, a step factor, and a one-parameter block

# For the array $data, call a block with the first element and then with each 3rd successor element
$data = [1,2,3,4,5,6,7,8]
$data.step(3) |$item| {
 notice($item)
}
# Puppet notices the values '1', '4', '7'.

When no block is given, Puppet returns a new Iterable which allows it to be directly chained into another function that takes an Iterable as an argument.

Example: Using the step function chained with a map function.

# For the array $data, return an array, set to the first element and each 5th successor element, in reverse
# order multiplied by 10
$data = Integer[0,20]
$transformed_data = $data.step(5).map |$item| { $item * 10 }
$transformed_data contains [0,50,100,150,200]

Example: The same example using step function chained with a map in alternative syntax

# For the array $data, return an array, set to the first and each 5th
# successor, in reverse order, multiplied by 10
$data = Integer[0,20]
$transformed_data = map(step($data, 5)) |$item| { $item * 10 }
$transformed_data contains [0,50,100,150,200]
  • Since 4.4.0

  • Type: rvalue

tag

Add the specified tags to the containing class or definition. All contained objects will then acquire that tag, also.

  • Type: statement

tagged

A boolean function that tells you whether the current container is tagged with the specified tags. The tags are ANDed, so that all of the specified tags must be included for the function to return true.

  • Type: rvalue

template

Loads an ERB template from a module, evaluates it, and returns the resulting value as a string.

The argument to this function should be a <MODULE NAME>/<TEMPLATE FILE> reference, which will load <TEMPLATE FILE> from a module’s templates directory. (For example, the reference apache/vhost.conf.erb will load the file <MODULES DIRECTORY>/apache/templates/vhost.conf.erb.)

This function can also accept:

  • An absolute path, which can load a template file from anywhere on disk.
  • Multiple arguments, which will evaluate all of the specified templates and return their outputs concatenated into a single string.

  • Type: rvalue

type

Returns the data type of a given value with a given degree of generality.

type InferenceFidelity = Enum[generalized, reduced, detailed]

function type(Any $value, InferenceFidelity $fidelity = 'detailed') # returns Type

Example: Using type

puppet notice type(42) =~ Type[Integer]

Would notice true.

By default, the best possible inference is made where all details are retained. This is good when the type is used for further type calculations but is overwhelmingly rich in information if it is used in a error message.

The optional argument $fidelity may be given as (from lowest to highest fidelity):

  • generalized - reduces to common type and drops size constraints
  • reduced - reduces to common type in collections
  • detailed - (default) all details about inferred types is retained

Example: Using type() with different inference fidelity:

puppet notice type([3.14, 42], 'generalized') notice type([3.14, 42], 'reduced'') notice type([3.14, 42], 'detailed') notice type([3.14, 42])

Would notice the four values:

  1. ‘Array[Numeric]’
  2. ‘Array[Numeric, 2, 2]’
  3. ‘Tuple[Float[3.14], Integer[42,42]]]’
  4. ‘Tuple[Float[3.14], Integer[42,42]]]’
  • Since 4.4.0

  • Type: rvalue

versioncmp

Compares two version numbers.

Prototype:

$result = versioncmp(a, b)

Where a and b are arbitrary version strings.

This function returns:

  • 1 if version a is greater than version b
  • 0 if the versions are equal
  • -1 if version a is less than version b

Example:

if versioncmp('2.6-1', '2.4.5') > 0 {
    notice('2.6-1 is > than 2.4.5')
}

This function uses the same version comparison algorithm used by Puppet’s package type.

  • Type: rvalue

warning

Log a message on the server at level warning.

  • Type: statement

with

Call a lambda with the given arguments and return the result. Since a lambda’s scope is local to the lambda, you can use the with function to create private blocks of code within a class using variables whose values cannot be accessed outside of the lambda.

Example: Using with

# Concatenate three strings into a single string formatted as a list.
$fruit = with("apples", "oranges", "bananas") |$x, $y, $z| {
  "${x}, ${y}, and ${z}"
}
$check_var = $x
# $fruit contains "apples, oranges, and bananas"
# $check_var is undefined, as the value of $x is local to the lambda.
  • Since 4.0.0

  • Type: rvalue


This page autogenerated on 2016-09-22 14:44:52 -0700

↑ Back to top