10

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?

Alex Cohen
  • 5,596
  • 16
  • 54
  • 104

1 Answers1

10

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.

Dessa Simpson
  • 1,232
  • 1
  • 15
  • 30
user1571135
  • 199
  • 1
  • 7
  • In the above examples, it's not clear to me how `if $http_port {` and `if defined('$http_port') {` differ in terms of what they consider to be true/false. Can someone explain, please? – Jimadine Feb 22 '19 at 13:24
  • 2
    @Jimadine `if $http_port` is considered `true` only when `$http_port` is `defined` and is set to `true`. In all other cases this condition is not satisfied (is false). On the other hand `if defined('$http_port')` validates only whether variable `$http_port` is set to any value (is defined by value). In all other cases this condition will fail. – Daniel Hajduk Mar 19 '19 at 17:40
  • @DanielHajduk Thank you for the explanation! Makes sense now. – Jimadine Apr 10 '19 at 10:31
  • Per this https://stackoverflow.com/questions/74111016/puppet-manifest-check-if-variable-is-not-empty , this similar did not work, possibly not compatible with all version of puppet. – hare krshn Oct 18 '22 at 16:19