-1

Following this existing link - Puppet how to tell if a variable is set. which is , below is the piece of the puppet manifest script :

  if defined('$to_dir') {
    notify { "Fourthvalue of $from_dir and $to_dir ... ":}
    notify { "Fourth$to_dc... ":}
    $worker_name = "acme${port}_${machine}${from_dir}_${to_dir}"
    $system_id = "${machine}${from_dir}.${to_dir}
  } else {
    $worker_name = "acme${port}_${machine}_${pod}"
    $system_id = $::fqdn
  }

However, when we pass "to_dir" as null, it is still going into if block as actual(expect to be in else block).

Even tried using if $to_dir { or if $to_dir != undef { , this did not help.

The value of "to_dir" will be a word either "abc" or "def".

Please advise if something is wrong..

hare krshn
  • 176
  • 1
  • 4
  • 16

2 Answers2

1

puppet manifest check if variable is not empty

You're throwing around a variety of terms -- "defined", "empty", "null" -- that mean different things or nothing in Puppet. But taken in toto, I think your purpose would be served by testing whether the variable in question is defined and contains a nonempty string. You can do that by matching the variable against an appropriate type expression. For example,

if $to_dir =~ String[1] {
  # ...
}

That tests that variable $to_dir contains a string at least one character long. The condition will evaluate to false if $to_dir has not been assigned a value, or if it has been assigned a value of a type different from String, or if its value is an empty string. If the value is a string, it puts no other requirements on the contents. In particular, the value could consist only of one or more space characters.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157
  • Note: this will work with Puppet version 4 or later, which includes all versions that are still supported and some that aren't. But there are some very old versions of Puppet still in use in the wild with which it would not work. – John Bollinger Oct 19 '22 at 18:46
0

i think the main issue here is that a variable which is instantiated with $var = undef is a defined variable with a value set to undef (its imo not well named). that said you checking the truthy state or undef (or using something specific to the datatype like size or empty) should all work. e.g.

# at this point defined('$var') == false
$var = undef
# now defined('$var') evalutes to false
# you should be able to check with the following that evaluate to true
($var == undef)
!$var
# you can also use the following which evaluates to false
$var =~ NotUndef
balder
  • 734
  • 5
  • 12