puppet:遍历具有特定值数组的散列

puppet: iterate over hash which has an array for particular values

我有一个散列,它是通过 stdlib 从 yaml 构建的,其中包括散列中的数组。这是 yaml 的示例:

datacenter1:
  propertyA:
    - associatedItem
  cage1:
    serviceA:
    - server1
    - server2
    serviceB:
    - server10
    backupCage:
      cage2
  cage2:
   serviceA:
    - server3
    - server4
    - server5
   serviceB:
    - server11
   backupCage:
     cage1
datacenter2:
  cage1:
    serviceA:
    - server20
    - server21
datacenter3:
  propertyZ:
    serviceD:
    - server200
    - server201

在这种情况下,我需要获取在 erb 的特定数据中心内提供服务的服务器列表。最终,这只需要以文本形式输出,并为 conf 文件添加一些任意数据。我试图让所有服务器为给定的数据中心提供 serviceA,在此示例中为 datacenter1:

thiscommand blahblah server1 
thiscommand blahblah server2
thiscommand blahblah server3
thiscommand blahblah server4
thiscommand blahblah server5

我将此映射广泛用于各种用途,但这是第一个我不能在 puppet 中设置变量并在 erb 中将其作为单个数组迭代的情况。

编辑1: 该数据来自 puppet,但我试图通过模板 () 在 erb 中使用它。

编辑2: 请注意,此代码永远不会 运行 针对 datacenter3,因为此代码特定于 运行 serviceA 的数据中心。

编辑3: 这是最终起作用的形式: <% @hash['datacenter1'].values.each 做 |v| %>

 <%- if v.is_a?(Hash) and v.has_key?('serviceA') -%> 

   <% v['serviceA'].each do |myservice| %>

         thiscommand blah blah <%= myservice -%> 

     <% end %>

  <% end %>

目前尚不清楚您是在 Puppet 中还是在 Ruby 中尝试执行此操作,下面是如何在两者中执行此操作。

人偶:

$hash['datacenter1'].each |$dc_key, $dc_nest_hash| {
  if $dc_nest_hash['serviceA'] {
    $dc_nest_hash['serviceA'].each |$serviceA_element| {
      notify { "thiscommand blahblah ${serviceA_element}": }
    }
  }
}

https://docs.puppet.com/puppet/4.9/function.html#each

Ruby 在通过 Puppet template 函数之前在 ERB 中(注释是对此答案的说明;在实际形成模板之前删除):

<% @hash['datacenter1'].each do |_, dc_nest_hash| -%>
  # contents of each datacenter1 nested hash in dc_nest_hash and iterate over each hash
  <%- if dc_nest_hash.key?('serviceA') -%>
    <%- dc_nest_hash['serviceA'].each do |serviceA_element| -%>
      # lookup serviceA key in each dc_nest_hash and iterate over elements
      thiscommand blahblah <%= serviceA_element %>
    <%- end -%>
  <%- end -%>>
<% end -%>

https://ruby-doc.org/core-2.1.1/Object.html#method-i-enum_for

http://ruby-doc.org/core-2.1.0/Array.html#method-i-each