I'd say the check depends on whether you want an alternative when the variable is not defined.
I'm using the following rules:
Required variable
Check in your puppet script whether the variable contains the expected value before even considering template rendering:
if $myvar == undef {
fail {"You really must set myvar, seriously."}
}
if ! $anothervar {
fail {"anothervar is false, undefined or empty."}
}
You can make your life easier by setting the type of parameters explicitly. This spares you type comparisons and conversions.
In your template you simply write the variables then:
<%= @myvar %>
<%= @anothervar %>
Optional variable that must be defined
If you assume the variable is defined, you can treat it as boolean.
The mapping is as follows (source):
- falsey: empty string, false, undef
- truthy: everything else
In Puppet >=4:
- falsey: false, undef
- truthy: everything else
Examples:
print 'something' if @myvar evaluates to true, otherwise 'something else'.
<% if @myvar %>something<% else %>something else<% end %>
print 'something' if @myvar evaluates to true
<% if @myvar %>something<% end %>
print @myvar if it evaluates to true, otherwise 'alternative' %>
<%= @myvar ? @myvar : 'alternative' %>
Optional variable that may be defined
If you are not sure a variable is even defined and don't want to make wrong assumptions, check it in the template.
Examples:
print 'something' followed by @myvar if @myvar is defined and not empty
<% if defined?(@myvar) && ! @myvar.empty? %>something<%= @myvar %><% end %>
print @myvar if it's defined and greater than 10
<%= @myvar if defined?(@myvar) && @myvar > 10 %>