从 Puppet 中的哈希数组中提取值数组

Extracting an array of values from an array of hashes in Puppet

我在 hiera 中有以下哈希数组:

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_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 中遗漏了一些逻辑,要么我可能为此完全使用了错误的函数。

我想知道是否有更好的方法来实现我想要做的事情?

But I suspect there must be a better way of doing this and I am either missing some logic in my map or I am likely using the wrong function altogether for this.

map() 为每个输入项恰好发出一个输出项,因此如果您的 objective 是应用单个函数从您的(更长的)输入中获取您想要的输出,那么确实,map 达不到那个目的。

I would like to know if there is a better way to achieve what I am trying to do?

就我个人而言,我会通过 filter 从您的输入中提取出您想要的哈希值,然后 mapping 那些到想要的输出形式(而不是 map ping 然后 filtering 结果):

$global_admins = $corporate_roles.filter |$hash| {
    $hash['global_administrator']
  }.map |$hash| { $hash['name'] }

我喜欢它,因为它很好而且清晰,但是如果你想用一个函数调用而不是两个函数调用来完成它,那么你可能正在寻找 reduce:

$global_admins = $corporate_roles.reduce([]) |$admins, $hash| {
  $hash['global_admin'] ? {
    true    => $admins << $hash['name'],
    default => $admins
  }
}