puppet:迭代散列,其中包含特定值的数组

问题描述:

我有一个散列,通过stdlib从yaml构建,其中包含散列内的数组。这里是YAML的一个示例:在这种情况下,我需要得到其报价在ERB一个特定的数据中心内的服务的服务器列表puppet:迭代散列,其中包含特定值的数组

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 

。最终,这只需要在文本中输出一些为conf文件添加的任意数据。我想获得一个给定的数据中心提供serviceA所有服务器,在这个例子datacenter1:

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

我大量使用本地图各种各样的事情,但是这是第一例,我可以”只需在puppet中设置一个变量并将其作为erb中的单个数组迭代即可。

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

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

编辑3: 这是结束工作的表格: <%@hash ['datacenter1']。values.each do | v | %>

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

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

     thiscommand blah blah <%= myservice -%> 

    <% end %> 

    <% end %> 

目前还不清楚,如果你正在尝试中木偶或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

红宝石ERB通过木偶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

+0

该数据来自puppet,但我试图在erb中使用它。使用你写的作为一个起点,我几乎可以使用我上面发布的编辑(主要是更多的'dos')。 – pozcircuitboy

+0

仍然不满意该语法: ' - :6:语法错误,意外',',期待输入结束 ; @hash ['datacenter1']。each | cage_key,cage_values | do' 错误胡萝卜位于分隔cage_key和cage_values的空格处 – pozcircuitboy

+0

解析器模板失败 .erb在第7行。第7行是: '' 详细信息:未定义的方法'each'for nil:NilClass' 一旦我得到了这个,我可以为每个数据中心名打包另一个循环,我假设。 – pozcircuitboy