Using Ruby in ERB templates

To manipulate and print data in ERB templates, you’ll need to know some Ruby. A full introductory Ruby tutorial is outside the scope of these docs, but this page provides an overview of Ruby basics commonly used in ERB templates.

Using if statements

The if ... end statement in Ruby lets you write conditional text. Put the control statements in non-printing tags, and the conditional text between the tags:

<% if <CONDITION> %> text goes here <% end %>
For example:
<% if @broadcast != "NONE" %>broadcast <%= @broadcast %><% end %>
The general format of an if statement is:
if <CONDITION>
  ... code ...
elsif <CONDITION>
  ... other code ...
end

Using iteration

Ruby lets you iterate over arrays and hashes with the each method. This method takes a block of code and executes it one time for each element in the array or hash. In a template, untagged text is treated as part of the code that gets repeated. You can think of literal text as an instruction, telling the evaluator to insert that text into the final output.

To write a block of code in Ruby, use either do |arguments| ... end or {|arguments| ... }. Note that this is different from Puppetlambdas — but they work similarly.

<% @values['each'] do |val| -%>
Some stuff with <%= val %>
<% end -%>
If $values was set to ['one', 'two'], this example would produce:
Some stuff with one
Some stuff with two
This example also trims line breaks for the non-printing tags, so they won’t appear as blank lines in the output.

Manipulating data

Your templates generally use data from Puppet variables. These values almost always be strings, numbers, arrays, and hashes.

These become the equivalent Ruby objects when you access them from an ERB template.

For information about the ways you can transform these objects, see the Ruby documentation for strings, integers, arrays, and hashes.

Also, note that the special undef value in Puppet becomes the special nil value in Ruby in ERB templates.