Search code examples
puppet

If behavior in puppet


In global variables I have hash like string key : array value. Also I have host name from facts.

I am trying to check if that host is inside any of arrays in the hash. If yes, variable value = key. And then use that data.

    $mygroup = undef

    notice("mygroup before is: ${$mygroup}")
    notify{"mygroup before is: ${$mygroup}": }

    $group_servers.each |$groupserver, $servers| {
        if ($hostname in $servers) {
            $mygroup = $groupserver
            notice("mygroup in if is: ${$mygroup}")
            notify{"mygroup in if is: ${$mygroup}": }
        }
    }

    notice("mygroup after is: ${$mygroup}")
    notify{"mygroup after is: ${$mygroup}": }

But what I have inside if I got the required data in the variable. But outside if it is again empty... Maybe try to use arrays? To add $groupserver to it... or in puppet it works differently and everything needs to put inside if? That will producoea mess of if inside if inside something else. =)

p.s. Solved

$my_groups = $group_servers.filter |$value| {
    $hostname in $value[1]
}

$onegroup = $my_groups.map |$g| { $g[0] }
$mygroup = $onegroup[0]

Solution

  • Puppet variables may be assigned values only once. There can be different variables with the same name in different scopes, each one can be assignable once, but an assignment to one such variable is not visible via a different one.

    You need to assign the wanted value in the first place, instead of relying on reassignment. For complex situations you might need to write a custom function for that, or in certain cases you might be able to use a template, but in this case, Puppet has built-in functions that can do the job. For example,

    $mygroup = $group_servers.reduce(undef) |$group, $kv| {
      ($hostname in $kv[1]) ? { true => $kv[0], default => $group }
    }
    

    That takes the last matching group seen if the hostname appears in more than one, which seems consistent with the intent of the non-working code in the question.

    A lot of computations that revolve around transforming or processing arrays and / or hashes can be written in terms of various Puppet iteration functions. Among those, reduce, used above, is perhaps the most powerful.