One of my very early frustrations with puppet was that it allows variables to be used when they were undefined. Primarily this bit me by not catching typos in variable names which were often very hard to track down. I was very pleased when Puppetlabs introduced a strict_variables mode which throws an error if a manifest attempts to use an undefined variable.

I recently need to check for the existence of a fact. Without strict_variables, this is straight-forward:

if $::some_fact {
  # do stuff here
}

If the fact "some_fact" exists, the variable is a non-empty string and evaluates as true in boolean context. If the fact doesn't exist, the variable is an empty string which evaluates as false in boolean context.

But, with strict_variables enforced, this throws an error:

Error: Undefined variable "::some_fact"; Undefined variable "some_fact" at line ...

The solution is to use the getvar function from stdlib:

if getvar('::some_fact') {
  # do stuff here
}

This works exactly the same as in the previous example, but doesn't throw an error if "some_fact" doesn't exist.

4 thoughts on “Test for undefined fact in puppet with strict_variables

  1. seems it still output warning messages…

     

    Warning: Scope(Class[main]): Could not look up qualified variable '::some_fact';

  2. This workaround doesn't work for me either, tested on puppet 4.x and 3.x. What stdlib version do you use?

Leave a reply

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

required