Docs: Function Reference


Function Reference

Function Reference

This page is autogenerated; any changes will get overwritten (last generated on Mon Mar 18 10:53:59 -0700 2013)

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

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',
              group  => allstaff,
              groups => ['developers', 'operations', 'release'], }
  'dan'  => { uid    => '1308',
              group  => 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)
  • 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

Determine whether a given class or resource type is defined. This function can also determine whether a specific resource has been declared. Returns true or false. Accepts class names, type names, and resource references.

The defined function checks both native and defined types, including types provided as plugins via modules. Types and classes are both checked using their names:

defined("file")
defined("customtype")
defined("foo")
defined("foo::bar")

Resource declarations are checked using resource references, e.g. defined( File['/tmp/myfile'] ). Checking whether a given resource has been declared is, unfortunately, dependent on the parse order of the configuration, and the following code will not work:

if defined(File['/tmp/foo']) {
    notify("This configuration includes the /tmp/foo file.")
}
file {"/tmp/foo":
    ensure => present,
}

However, this order requirement refers to parse order only, and ordering of resources in the configuration graph (e.g. with before or require) does not affect the behavior of defined.

  • Type: rvalue

emerg

Log a message on the server at level emerg.

  • Type: statement

err

Log a message on the server at level err.

  • Type: statement

extlookup

This is a parser function to read data from external files, this version uses CSV files but the concept can easily be adjust for databases, yaml or any other queryable data source.

The object of this is to make it obvious when it’s being used, rather than magically loading data in when an module is loaded I prefer to look at the code and see statements like:

$snmp_contact = extlookup("snmp_contact")

The above snippet will load the snmp_contact value from CSV files, this in its own is useful but a common construct in puppet manifests is something like this:

case $domain {
  "myclient.com": { $snmp_contact = "John Doe <[email protected]>" }
  default:        { $snmp_contact = "My Support <[email protected]>" }
}

Over time there will be a lot of this kind of thing spread all over your manifests and adding an additional client involves grepping through manifests to find all the places where you have constructs like this.

This is a data problem and shouldn’t be handled in code, a using this function you can do just that.

First you configure it in site.pp:

$extlookup_datadir = "/etc/puppet/manifests/extdata"
$extlookup_precedence = ["%{fqdn}", "domain_%{domain}", "common"]

The array tells the code how to resolve values, first it will try to find it in web1.myclient.com.csv then in domain_myclient.com.csv and finally in common.csv

Now create the following data files in /etc/puppet/manifests/extdata:

domain_myclient.com.csv:
  snmp_contact,John Doe <[email protected]>
  root_contact,support@%{domain}
  client_trusted_ips,192.168.1.130,192.168.10.0/24

common.csv:
  snmp_contact,My Support <[email protected]>
  root_contact,[email protected]

Now you can replace the case statement with the simple single line to achieve the exact same outcome:

$snmp_contact = extlookup("snmp_contact")

The above code shows some other features, you can use any fact or variable that is in scope by simply using %{varname} in your data files, you can return arrays by just having multiple values in the csv after the initial variable name.

In the event that a variable is nowhere to be found a critical error will be raised that will prevent your manifest from compiling, this is to avoid accidentally putting in empty values etc. You can however specify a default value:

$ntp_servers = extlookup("ntp_servers", "1.${country}.pool.ntp.org")

In this case it will default to “1.${country}.pool.ntp.org” if nothing is defined in any data file.

You can also specify an additional data file to search first before any others at use time, for example:

$version = extlookup("rsyslog_version", "present", "packages")
package{"rsyslog": ensure => $version }

This will look for a version configured in packages.csv and then in the rest as configured by $extlookup_precedence if it’s not found anywhere it will default to present, this kind of use case makes puppet a lot nicer for managing large amounts of packages since you do not need to edit a load of manifests to do simple things like adjust a desired version number.

Precedence values can have variables embedded in them in the form %{fqdn}, you could for example do:

$extlookup_precedence = ["hosts/%{fqdn}", "common"]

This will result in /path/to/extdata/hosts/your.box.com.csv being searched.

This is for back compatibility to interpolate variables with %. % interpolation is a workaround for a problem that has been fixed: Puppet variable interpolation at top scope used to only happen on each run.

  • Type: rvalue

fail

Fail with a parse error.

  • Type: statement

file

Return the contents of a file. Multiple files can be passed, and the first file that exists will be read in.

  • Type: rvalue

fqdn_rand

Generates random numbers based on the node’s fqdn. Generated random values will be a range from 0 up to and excluding n, where n is the first parameter. The second argument specifies a number to add to the seed and is optional, for example:

$random_number = fqdn_rand(30)
$random_number_seed = fqdn_rand(30,30)
  • 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 and returns the most specific value for a given key. The returned value can be data of any type (strings, arrays, or hashes).

In addition to the required key argument, hiera accepts two additional arguments:

  • a default argument in the second position, providing a value to be returned in the absence of matches to the key argument
  • an override argument in the third position, providing a data source to consult for matching values, even if it would not ordinarily be part of the matched hierarchy. If Hiera doesn’t find a matching key in the named override data source, it will continue to search through the rest of the hierarchy.

More thorough examples of hiera are available at: http://docs.puppetlabs.com/hiera/1/puppet.html#hiera-lookup-functions

  • Type: rvalue

hiera_array

Returns all matches throughout the hierarchy — not just the first match — as a flattened array of unique values. If any of the matched values are arrays, they’re flattened and included in the results.

In addition to the required key argument, hiera_array accepts two additional arguments:

  • a default argument in the second position, providing a string or array to be returned in the absence of matches to the key argument
  • an override argument in the third position, providing a data source to consult for matching values, even if it would not ordinarily be part of the matched hierarchy. If Hiera doesn’t find a matching key in the named override data source, it will continue to search through the rest of the hierarchy.

If any matched value is a hash, puppet will raise a type mismatch error.

More thorough examples of hiera are available at: http://docs.puppetlabs.com/hiera/1/puppet.html#hiera-lookup-functions

  • Type: rvalue

hiera_hash

Returns a merged hash of matches from throughout the hierarchy. In cases where two or more hashes share keys, the hierarchy order determines which key/value pair will be used in the returned hash, with the pair in the highest priority data source winning.

In addition to the required key argument, hiera_hash accepts two additional arguments:

  • a default argument in the second position, providing a hash to be returned in the absence of any matches for the key argument
  • an override argument in the third position, providing a data source to insert at the top of the hierarchy, even if it would not ordinarily match during a Hiera data source lookup. If Hiera doesn’t find a match in the named override data source, it will continue to search through the rest of the hierarchy.

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 will raise a type mismatch error.

More thorough examples of hiera_hash are available at: http://docs.puppetlabs.com/hiera/1/puppet.html#hiera-lookup-functions

  • Type: rvalue

hiera_include

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

To use hiera_include, the following configuration is required:

  • A key name to use for classes, e.g. classes.
  • A line in the puppet sites.pp file (e.g. /etc/puppet/manifests/sites.pp) reading hiera_include('classes'). Note that this line must be outside any node definition and below any top-scope variables in use for Hiera lookups.
  • Class keys in the appropriate data sources. In a data source keyed to a node’s role, one might have:

        ---
        classes:
          - apache
          - apache::passenger
    

In addition to the required key argument, hiera_include accepts two additional arguments:

  • a default argument in the second position, providing an array to be returned in the absence of matches to the key argument
  • an override argument in the third position, providing a data source to consult for matching values, even if it would not ordinarily be part of the matched hierarchy. If Hiera doesn’t find a matching key in the named override data source, it will continue to search through the rest of the hierarchy.

More thorough examples of hiera_include are available at: http://docs.puppetlabs.com/hiera/1/puppet.html#hiera-lookup-functions

  • Type: statement

include

Evaluate one or more classes.

  • Type: statement

info

Log a message on the server at level info.

  • Type: statement

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

md5

Returns a MD5 hash value from a provided string.

  • 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

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.

  • Type: statement

Add another namespace for this class to search. This allows you to create classes with sets of definitions and add those classes to another class’s search path.

  • Type: statement

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

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, '[.:]')

$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

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

Evaluate a template and return its value. See the templating docs for more information.

Note that if multiple templates are specified, their output is all concatenated and returned as the output of the function.

  • 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

This page autogenerated on Mon Mar 18 10:53:59 -0700 2013

↑ Back to top