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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With