Suppress Blank Lines in Puppet Templates

When writing an ERB template for Puppet, it is often that case that you want to emit a line of text if and only if a variable has been assigned a value.

Here is a template used to create jail.local files for fail2ban.

[<%= @name %>]

<% unless @action.nil? %>action = <%= @action %><% end %>
<% unless @backend.nil? %>backend = <%= @backend %><% end %>
<% unless @bantime.nil? %>bantime = <%= @bantime %><% end %>
<% unless @enabled.nil? %>enabled = <%= @enabled %><% end %>
<% unless @failregex.nil? %>failregex = <%= @failregex %><% end %>
<% unless @filter.nil? %>filter = <%= @filter %><% end %>
<% unless @findtime.nil? %>findtime = <%= @findtime %><% end %>
<% unless @ignorecommand.nil? %>ignorecommand = <%= @ignorecommand %><% end %>
<% unless @ignoreip.nil? %>ignoreip = <%= @ignoreip %><% end %>
<% unless @ignoreregex.nil? %>ignoreregex = <%= @ignoreregex %><% end %>
<% unless @logpath.nil? %>logpath = <%= @logpath %><% end %>
<% unless @maxretry.nil? %>maxretry = <%= @maxretry %><% end %>
<% unless @port.nil? %>port = <%= @port %><% end %>
<% unless @usedns.nil? %>usedns = <%= @usedns %><% end %>

The output you would like is this:

[nginx-noscript]

    enabled = true
    filter = nginx-noscript
    logpath = /var/log/nginx/access.log
    maxretry = 2
    port = http,https

What you get is this.

[nginx-noscript]




enabled = true

filter = nginx-noscript




logpath = /var/log/nginx/access.log
maxretry = 2
port = http,https

The solution, as it turns out, is not to fool with ERB trim mode. Instead it is better to be explicit in the template. What you really want is to emit, say,

action = moof

followed by a newline if @action is set, or nothing if @action is not set. The following template expresses this.

[<%= @name %>]

<% unless @action.nil? %>action = <%= @action %>
<% end %><% unless @backend.nil? %>backend = <%= @backend %>
<% end %><% unless @bantime.nil? %>bantime = <%= @bantime %>
<% end %><% unless @enabled.nil? %>enabled = <%= @enabled %>
<% end %><% unless @failregex.nil? %>failregex = <%= @failregex %>
<% end %><% unless @filter.nil? %>filter = <%= @filter %>
<% end %><% unless @findtime.nil? %>findtime = <%= @findtime %>
<% end %><% unless @ignorecommand.nil? %>ignorecommand = <%= @ignorecommand %>
<% end %><% unless @ignoreip.nil? %>ignoreip = <%= @ignoreip %>
<% end %><% unless @ignoreregex.nil? %>ignoreregex = <%= @ignoreregex %>
<% end %><% unless @logpath.nil? %>logpath = <%= @logpath %>
<% end %><% unless @maxretry.nil? %>maxretry = <%= @maxretry %>
<% end %><% unless @port.nil? %>port = <%= @port %>
<% end %><% unless @usedns.nil? %>usedns = <%= @usedns %>
<% end %>