Leveraging the new template engine

In Chapter 6, Leveraging the Full Toolset of the Language, we introduced templates and the ERB template engine. In Puppet 4, an alternative was added: the EPP template engine. The major differences between the template engines are as follows:

  • In ERB templates, you cannot specify a variable in Puppet syntax ($variable_name)
  • ERB templates will not accept parameters
  • In EPP templates, you will use the Puppet DSL syntax instead of Ruby syntax

The EPP template engine requires scoped variables from modules:

# motd file – managed by Puppet
This system is running on <%= $::operatingsystem %>

The manifest defines the following local variable: <%= $motd::local_variable %>. The EPP templates also have a unique extension; they can take typed parameters. To make use of this, a template has to start with a parameter declaration block:

<%- | String $local_variable,
      Array  $local_array
| -%>

These parameters are not like variables from Puppet manifests. Instead, one must pass parameters using the epp function:

epp('template/test.epp', {'local_variable' => 'value', 'local_array' => ['value1', 'value2'] })

A template without parameters should only be used when the template is used exclusively by one module, so that it is safe to rely on the availability of Puppet variables to customize the content.

Using the EPP template function with parameters is recommended when a template is used from several places. By declaring the parameters at the beginning, it is especially clear what data the template requires.

There is a specific difference between the template engines when iterating over arrays and hashes. The ERB syntax uses Ruby code with unscoped, local variables, whereas the EPP syntax requires specifying Puppet DSL code:

# ERB syntax
<% @array.each do |element| -%>
<%= element %>
<% end -%>

# EPP syntax
<% $array.each |$element| { -%>
<%= $element %>
<% } -%>

The inline ERB function was also supplemented with inline EPP. Using the inline EPP, one can specify a small snippet of EPP code to get evaluated:

file {'/etc/motd':
  ensure  => file,
  content => inline_epp("Welcome to <%= $::fqdn %>
")
}

Prior to Puppet 4, it was inconvenient to pass more than a small code snippet. With Puppet 4 and the HEREDOC support, complex templates in combination with inline_epp are easier and better readable.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset