Arrays 从Puppet中的哈希数组中提取值数组
我在hiera中有以下哈希数组:Arrays 从Puppet中的哈希数组中提取值数组,arrays,hash,puppet,hiera,Arrays,Hash,Puppet,Hiera,我在hiera中有以下哈希数组: corporate_roles: - name: 'user.1' system_administrator: true global_administrator: false password: TestPassword1234 - name: 'user.2' system_administrator: true global_administrator: true password: TestPass
corporate_roles:
- name: 'user.1'
system_administrator: true
global_administrator: false
password: TestPassword1234
- name: 'user.2'
system_administrator: true
global_administrator: true
password: TestPassword1234
我需要提取具有给定角色(例如global\u administrator
)的用户列表,以便稍后分配。
我设法使用map
功能提取我需要的数据:
$corporate_roles = lookup('corporate_roles')
$global_admins = $corporate_roles.map | $hash | { if ($hash['global']){$hash['name']}}
notify { "global admins are: ${global_admins}":
}
但是,对于不符合条件的用户,这会导致undef
值似乎进入数组:
Notice: /Stage[main]/salesraft_test/Notify[global admins are: [, user.2]]/message: defined 'message' as 'global admins are: [, user.2]'
Notice: Applied catalog in 0.04 seconds
我可以通过使用filter
函数来解决这个问题:
$test = $global_admins.filter | $users | {$users =~ NotUndef}
这将产生干净的输出:
Notice: /Stage[main]/salesraft_test/Notify[global admins are: [user.2]]/message: defined 'message' as 'global admins are: [user.2]'
Notice: Applied catalog in 0.03 seconds
但我怀疑一定有更好的方法来实现这一点,我要么在我的映射中缺少一些逻辑,要么我可能为此使用了错误的函数
我想知道是否有更好的方法来实现我的目标
但我怀疑一定有更好的方法,我也不是
地图中缺少一些逻辑,或者我可能使用了错误的函数
完全是为了这个
map()
只为每个输入项发出一个输出项,因此如果您的目标是应用单个函数从(较长的)输入中获得所需的输出,那么实际上,map
将无法实现这一点
我想知道是否有更好的方法来实现我的目标
就我个人而言,我会通过过滤
从输入中提取出所需的哈希值,然后映射
将这些哈希值ping到所需的输出表单(而不是映射
ping,然后过滤
结果):
我喜欢这一点,因为它既漂亮又清晰,但是如果你想用一个函数调用而不是两个函数调用,那么你可能需要:
$global_admins=$corporate_roles.reduce([])|$admins,$hash |{
$hash['global_admin']{
true=>$admins$admins
}
}
这样做非常有效,使事情更加清晰。非常感谢。
$global_admins = $corporate_roles.filter |$hash| {
$hash['global_administrator']
}.map |$hash| { $hash['name'] }
$global_admins = $corporate_roles.reduce([]) |$admins, $hash| {
$hash['global_admin'] ? {
true => $admins << $hash['name'],
default => $admins
}
}