Check if a variable is undef in puppet template

The Puppet documentation (at the time of writing this answer) explains it very well: https://puppet.com/docs/puppet/latest/lang_template_erb.html#concept-5365

Since undef is not the same as false, just using an if is not a good way to check for it. Also when a variable is defined, but has a value of false or nil it is also impossible to check with a simple if.

This is why you want to use scope.lookupvar(‘variable’) and check its return value for :undef or :undefined (or nil) to know if it was set to undef, or never set at all.


The first one should work like a charm, it's what is being taught in the courses as well.

Number two seems... redundant.


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 %>

Tags:

Erb

Puppet