22

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?

4

3 回答 3

9

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.

于 2014-07-13T16:08:11.617 回答
7

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 %>
于 2016-12-07T09:44:43.813 回答
2

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

Number two seems... redundant.

于 2013-06-14T05:09:19.403 回答