Search code examples
puppetpuppet-enterprise

How to check multiple variable is empty or not in Puppet 4.x


I am trying to check two or more variables is empty or not. To achieve it, I found the following way.

if $path {
    if $name {
          notify { "Path : ${path}": }
          notify { "Name : ${name}": }
    }
}

If we need to check more than two variables, How to check it out ?

Please suggest any best way to code.


Solution

  • I am trying to check two or more variables is empty or not.

    I take you to mean that you want to determine whether any of several variables is an empty string. You can use the new reduce() function to solve this problem.

    For example, this ...

    $is_any_empty = reduce([$one, $two, $three], false) |$memo, $entry| {
        $memo or ($entry == '')
    }
    

    ... sets variable $is_any_empty to true if and only if at least one of the variables $one, $two, and $three contains an empty string, which is what you asked.

    Even with your clarification, though, I suspect that's not exactly what you really want. My best guess is that you actually want to determine whether all of a set of variables have values that are non-empty strings (as opposed to being undefined or having values that are not strings at all). That kind of type-aware checking can be done with the help of Puppet 4's new type system:

    $all_are_nonempty = reduce([$one, $two, $three], true) |$memo, $entry| {
        $memo and ($entry =~ String[1])
    }
    

    The $entry =~ String[1] is a boolean expression evaluating to whether the value of variable $entry has type String and is at least one character long. Do note that it will match strings consisting of only spaces; if you don't want that then the needed mods are left as an exercise.