puppet:迭代hash,它有一个特定值的数组

时间:2017-02-20 23:12:27

标签: arrays hash puppet erb

我有一个哈希,由yaml通过stdlib构建,其中包含哈希中的数组。以下是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中作为单个数组迭代的情况。

EDIT1: 这个数据来自木偶,但我试图通过template()在erb中使用它。

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

EDIT3: 这是最终工作的形式:      <%@hash ['datacenter1']。values.each do | v | %GT;

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

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

         thiscommand blah blah <%= myservice -%> 

     <% end %>

  <% end %>

1 个答案:

答案 0 :(得分:1)

目前还不清楚你是否想在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中的ERB在通过Puppet template函数之前(注释是对这个答案的解释;在实际形成模板之前删除):

<% @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

相关问题