Skip to main content
Gå til innhold

Puppet templates

Puppet uses ERB as its templating language. This document will give a brief intro to ERB and list some common patterns/tips/tricks for using templates with our module/hiera setup.

Template files should be stored in the templates directory of a Puppet module, which allows the template function to locate them. For example, the file referenced by template("pmmodule_example/mytemplate.erb") is located at pmodule_example/templates/mytemplate.erb.

ERB syntax​

For a quick syntax description look at the official docs here:

http://docs.puppetlabs.com/guides/templating.html#erb-template-syntax

This page also includes most of the stuff below and is a good source of template documentation.

Note the different uses of tags, as listed here:

http://docs.puppetlabs.com/guides/templating.html#tags

The <%= form is the most used, and also note the <%- and -%> tags for supressing line breaks.

Example with patterns​

Here is a simple example with trac configuration template:

http://docs.puppetlabs.com/guides/templating.html#using-templates

The content option points to the template function, evaluating the template and using the result as the content of the file.

Using simple variables​

As seen in the Trac example above, variables are used with a @ prefix:

The value is <%= @myvar %>.

Looping arrays​

Assuming you have an array as $values you could loop the values like so:

<% @values.each do |val| -%>
Some stuff with <%= val %>
<% end -%>

Note the closing -%> tag to prevent the line with just code to produce a blank line.

Using hashes​

Hashes can be iterated similar to arrays, or just by keys or values. Assuming a hash as $hash:

<% @hash.each do |key, val| -%>
Some stuff with key <%= key %> has value <%= val %>
<% end -%>

Only keys:

<% @hash.keys.each do |key| -%>
Some stuff with key <%= key %>
<% end -%>

Only values:

<% @hash.values.each do |val| -%>
Some stuff with <%= val %>
<% end -%>

Conditionals​

Example if statement to conditionaly put a line in a /etc/network/interfaces-file:

<% if broadcast != "NONE" %> broadcast <%= broadcast %> <% end %>

All ruby conditionals can of course be used.

More information​

In addition to the official docs/ruby docs the best option might be to study templates allready written as part of our puppet modules:

https://gitlab.sikt.no/groups/puppet