Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppet how to tell if a variable is set

Tags:

puppet

In a puppet class how should I test if a variable has been set or not? Right now I am just checking if a variable is undefined:

if $http_port != undef {
  $run_command = "$run_command --http-port $http_port"
}

Is there a better way to check if a variable has been declared or not?

like image 664
Alex Cohen Avatar asked Jul 25 '17 17:07

Alex Cohen


1 Answers

If you are testing if an variable is undef, your way is correct. Writing

if $http_port {
  $run_command = "$run_command --http-port $http_port"
}

would accomplish almost the same. If $http_port is undef or false, it will not run the command.

If you want to test if the var has been defined you should do:

if defined('$http_port') {
  $run_command = "$run_command --http-port $http_port"
}

See https://docs.puppet.com/puppet/4.10/function.html#defined.

If the var is a class variable you could do something like:

class your_class (
Optional[Integer[0, 65535]] $http_port = undef,
) {
    if $http_port {
      notify { "got here with http_port=${http_port}": }
    }
}

It will then only run the notify if the class is declared with http_port set as an integer between 0 and 65535.

like image 76
user1571135 Avatar answered Sep 22 '22 12:09

user1571135