Functions are pre-defined chunks of Ruby code which run during compilation. Most functions either return values or modify the catalog.
Puppet includes several built-in functions, and more are available in modules on the Puppet Forge, particularly the puppetlabs-stdlib module. You can also write custom functions and put them in your own modules.
file {'/etc/ntp.conf':
ensure => file,
content => template('ntp/ntp.conf'),
}
include apache2
if str2bool($is_virtual) {
include ntp::disabled
}
else {
include ntp
}
# str2bool is part of the puppetlabs-stdlib module; install it with
# sudo puppet module install puppetlabs-stdlib
In the examples above, template
, include
, and str2bool
are all functions. template
and str2bool
return values, and include
modifies the catalog by causing a class to be applied.
The general form of a function call is:
There are two types of Puppet functions:
template
function reads and evaluates a template to return a string, and stdlib’s str2bool
and num2bool
functions convert values from one data type to another.notice
), to modifying the catalog in progress (like include
), to causing the entire compilation to fail (fail
). Statements do not return usable values.All functions run during compilation, which means they can only access the commands and data available on the Puppet master. To perform tasks on, or collect data from, an agent node, you must use a resource or a custom fact.
Each function defines how many arguments it takes and what data types it expects those arguments to be. These should be documented in the function’s :doc
string, which can be extracted and included in the function reference.
Functions may accept any of Puppet’s standard data types. The values passed to the function’s Ruby code will be converted to Ruby objects as follows:
Puppet type | Ruby type |
---|---|
boolean | boolean |
undef | the empty string |
string | string |
resource reference | Puppet::Resource |
number | string |
array | array |
hash | hash |