A collection of task oriented solutions in Puppet

 

Syntax check your ERB templates

Challenge

Check your ERB (Embedded RuBy) templates for syntax errors

Solution

# Invalid ERB template - /tmp/broken.erb
<% if @server -%>
  server  <%= @server > # ERROR: this line should end '%>'
<% end -%>
# check the syntax
/opt/puppetlabs/puppet/bin/erb -P -x -T '-' \
  /tmp/broken.erb \
  | /opt/puppetlabs/puppet/bin/ruby -c

# and we get the unfriendly error
-:4: syntax error, unexpected '<'
<% end ).to_s)
 ^
-:5: syntax error, unexpected end-of-input, expecting keyword_end

Explanation

It's easy to make a mistake in your ERB (Embedded RuBy) templates when you're focused on writing manifests in the Puppet DSL but there's an easy way to create your own safety net to detect these issues early. By running your templates through the erb command and then having ruby parse them you can detect a number of common syntax errors.

# check the syntax
/opt/puppetlabs/puppet/bin/erb -P -x -T '-' \
  /tmp/broken.erb \
  | /opt/puppetlabs/puppet/bin/ruby -c

# and we get the unfriendly error
-:4: syntax error, unexpected '<'
<% end ).to_s)
 ^
-:5: syntax error, unexpected end-of-input, expecting keyword_end

The command line is quite opaque and lends itself to being wrapped, possibly in an alias, as suggested by Puppet:

validate_erb() {
  /opt/puppetlabs/puppet/bin/erb -P -x -T '-' "$1" | /opt/puppetlabs/puppet/bin/ruby -c
}

We use the bundled version of the commands located inside the /opt/puppetlabs/puppet/bin/ directory to avoid issues where you don't have a system level ruby install. It's also worth noting that command only provides a basic syntax check, it won't find misspelled properties or logic errors in your templates.

See also