What is the proper way to check if a variable is undef in a puppet template?
In the manifest the variable is defined as follows
$myvar = undef
How is this checked in the template?
Is saw the following two variants
<% if @myvar -%>
<% end -%>
and
<% if not @myvar.nil? and @myvar -%>
<% end -%>
They both seem to work in my case, but I wonder if the first approach fails in on certain cases?
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.