在全局变量中,我有类似字符串键的哈希:数组值。 我也有事实中的主机名。
我正在尝试检查该主机是否位于哈希中的任何数组内。如果是,变量值=键。 然后使用该数据。
$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}": }
但是我里面有什么
if
我在变量中得到了所需的数据。但外面if
又空了……
也许尝试使用数组?要向其中添加 $groupserver...或者在 puppet 中,它的工作方式有所不同,并且所有内容都需要放在里面if
?这会在其他东西里面产生 if
里面 if
的混乱。 =)
在Puppet中,变量在同一作用域内是不可变的。这意味着您不能在循环或 if 块内重新分配变量并期望它在该块外保留其新值。相反,您可以使用不同的方法来实现您的目标。
# Initialize an empty array to collect matching group names
$mygroups = []
notice("mygroups before is: ${mygroups}")
notify{"mygroups before is: ${mygroups}": }
# Iterate through the hash to find matching group names
$group_servers.each |$groupserver, $servers| {
if $hostname in $servers {
$mygroups += [$groupserver]
notice("mygroup in if is: ${groupserver}")
notify{"mygroup in if is: ${groupserver}": }
}
}
# Set the final mygroup variable based on the collected array
$mygroup = $mygroups.empty ? undef : $mygroups[0]
notice("mygroup after is: ${mygroup}")
notify{"mygroup after is: ${mygroup}": }