Evaluating ERB templates
After you have an ERB template, you can pass it to a function that evaluates it and returns a final string. The actual template can be either a separate file or a string value.
Evaluating ERB templates that are in a template file
Put template files in the templates
directory of a module.
ERB files use the .erb
extension.
To use a ERB template file, evaluate it with the template
function. For
example:
# template(<FILE REFERENCE>, [<ADDITIONAL FILES>, ...]) file { '/etc/ntp.conf': ensure => file, content => template('ntp/ntp.conf.erb'), # Loads /etc/puppetlabs/code/environments/production/modules/ntp/templates/ntp.conf.erb }
The first argument to the function is the file reference: a string in the form
'<MODULE>/<FILE>'
, which loads <FILE>
from <MODULE>
’s
templates directory. For example, the file reference activemq/amq/activemq.xml.erb
loads the <MODULES
DIRECTORY>/activemq/templates/amq/activemq.xml.erb
file.
The template function can take any number of additional template files, and concatenate their outputs together to produce the final string.
Evaluating ERB template strings
If you have a string value that contains template content, you can evaluate it with the
inline_template
function.
In older versions of Puppet, inline templates were mostly
used to get around limitations — tiny Ruby fragments were
useful for transforming and manipulating data before Puppet
had iteration functions like map
or puppetlabs/stdlib functions like chomp
and keys
.
In modern versions of Puppet, inline templates are usable in
some of the same situations template files are. Because the heredoc syntax makes it easy to write large and
complicated strings in a manifest, you can use inline_erb
to
reduce the number of files needed for a simple module that manages a small config file.
For example:
$ntp_conf_template = @(END) ...template content goes here... END # inline_template(<TEMPLATE STRING>, [<ADDITIONAL STRINGS>, ...]) file { '/etc/ntp.conf': ensure => file, content => inline_template($ntp_conf_template), }
The inline_template
function can take any number
of additional template strings, and concatenate their outputs together to produce the final
value.