Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 38 ยท Facts and Templates

ERB Templates and Legacy Code

Read and maintain Puppet's older ERB templates: the template() function, @variables, scope lookups, whitespace, and a safe path for migrating ERB files to EPP.

Before EPP existed, every Puppet template was written in ERB, the Embedded Ruby format used by Rails and many other tools. Thousands of public modules and many old control repositories still contain .erb files, so you need to read them even if you never write a new one. This lesson covers the syntax, the traps, and a step-by-step migration to EPP.

ERB works well enough, but it has two weaknesses compared with EPP: it is Ruby code running inside your Puppet compiler, and it reads variables from the surrounding class without declaring them. Both make templates harder to test and secure. Because the product cannot run on this site, code blocks are read-only and the runnable blocks are JavaScript stand-ins that imitate the lookups and the migration checks.

Using an ERB template

You render an ERB file with the template() function. The path has the same <module>/<file> form, and the file sits in templates/:

PUPPET
class motd (String $message = 'Authorized use only') {
  file { '/etc/motd':
    ensure  => file,
    content => template('motd/motd.erb'),
  }
}
ERB
<%# templates/motd.erb %>
<%= @message %>
Host: <%= @facts['networking']['fqdn'] %>
OS:   <%= @facts['os']['name'] %> <%= @facts['os']['release']['major'] %>

Notice the @ in front of the variable names. The template is evaluated as an object, and the class's variables are made available as instance variables. Without the @, Ruby does not see them. That one character is the most frequent ERB mistake for newcomers.

Syntax in short

Tag Meaning
<%= expr %> Insert a Ruby expression
<% code %> Execute Ruby, no output
<%# comment %> Comment
-%> Trim the following newline
<%- Trim leading whitespace

Loops and conditions are written in Ruby:

ERB
<% @servers.each do |s| -%>
server <%= s %> iburst
<% end -%>
<% if @enable_logging -%>
logfile /var/log/ntp.log
<% end -%>

Arrays and hashes passed from Puppet arrive as Ruby arrays and hashes. Puppet's undef becomes Ruby's nil (and sometimes :undef, depending on version), which is a classic source of bugs: always check with @value.nil? or scope.lookupvar rules rather than assuming a string.

Reaching other scopes

ERB can read variables that are not instance variables with scope:

ERB
<%= scope['::trusted']['certname'] %>
<%= scope.lookupvar('apache::port') %>

That is powerful and also a smell. A template that reaches into another class's variables is coupled to that class. If you must keep such code, add a comment that names the dependency. EPP forbids this style, and the migration (below) turns each scope lookup into an explicit parameter.

ERB is executable Ruby that runs on the Puppet server during compilation. Never render a template that contains code you do not trust, and never build template text from user-supplied data that could contain <%. EPP is safer because it only runs Puppet language code.

Common ERB mistakes

  • Missing @. <%= message %> raises an undefined method error because it is not a variable.
  • Wrong trim marker. A lone <% end %> leaves a blank line. Use -%>.
  • Mixed indentation. Ruby does not care, but the generated file does. Test the rendered output.
  • Using to_s implicitly. Booleans print as true/false; arrays print their inspect form. Join arrays yourself with .join(',').
  • Hidden nil. An unset parameter prints an empty string, which can produce a syntactically valid but wrong config line.

Migrating ERB to EPP

Convert one template at a time and keep the old file until the new one renders byte for byte the same text. A reliable procedure:

  1. List the variables. Scan the ERB for every @name and scope[...] call. Each becomes a parameter.
  2. Write the parameter tag at the top of the new .epp file, with types and defaults.
  3. Replace syntax. @name becomes $name; Ruby .each do |x| becomes .each |$x| { ... }; if x.nil? becomes if $x =~ Undef.
  4. Change the call site from template('mod/x.erb') to epp('mod/x.epp', { ... }), passing exactly the parameters you listed.
  5. Compare outputs. Render both, diff them, and only then delete the ERB file.
PUPPET
# before
content => template('ntp/ntp.conf.erb'),

# after
content => epp('ntp/ntp.conf.epp', {
  'servers' => $servers,
  'driftfile' => $driftfile,
}),

Stand-ins

The first block is a stand-in for what ERB does: it turns @name into a looked-up variable and flags names that are not defined. The second automates step 1 of the migration by scanning a template for variables.

JS Stand-in: @variable lookup and the undefined trap

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Stand-in: migration helper that lists template variables

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The report makes the migration to-do list concrete: two normal parameters and two scope lookups that must become arguments such as $certname and $apache_port.

When to keep ERB

  • A vendor module you do not own and update regularly: leave its templates alone.
  • A template that needs a Ruby feature EPP cannot express easily (rare; usually move the logic into a function or custom fact instead).
  • Code that must work on very old Puppet releases, where EPP is unavailable.

Everything else, write in EPP.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In an ERB template, how do you read the class variable $message?

    Class variables become Ruby instance variables, so the template uses @message.
  2. 2. Which is a security reason to prefer EPP over ERB?

    ERB executes Ruby during catalog compilation. EPP is limited to Puppet language code.
  3. 3. Which step comes first when migrating a template to EPP?

    The variable list becomes the parameter list of the new template.
  4. 4. What does scope['::trusted']['certname'] do in ERB?

    It looks up a variable outside the template's own parameters; EPP replaces this with explicit parameters.

Summary

  • template('mod/file.erb') renders ERB; class variables appear as @name.
  • ERB is Ruby on the server, so treat templates as code and keep them simple.
  • Common bugs: missing @, missing -%>, hidden nil, unjoined arrays.
  • Migrate one template at a time: list variables, declare parameters, convert syntax, change the call site, diff the output.
  • Write new templates in EPP.

Next: The Roles and Profiles Pattern