2017-02-20 8 views
1

yamlからstdlib経由で構築された、ハッシュ内の配列を含むハッシュを持っています。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 

私はERB内の特定のデータセンター内でのサービスを提供し、サーバのリストを取得する必要があり、この場合:ここではYAMLのサンプルです。最終的には、confファイル用に追加された任意のデータをテキストとして出力する必要があります。私はdatacenter1のために、この例では、すべてのサーバーが指定されたデータセンターのためのサービスAを提供する取得しようとしている:

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

私は物事の様々なために広く、このマップを使用しますが、これは「私ができるの最初のケースでありますpuppetの変数を設定し、それをerbの単一の配列として繰り返します。

EDIT1: このデータは人形のものですが、私はerbでtemplate()を使用しようとしています。

EDIT2: このコードは、serviceAを実行するデータセンターに固有のものであるため、datacenter3に対して実行されることはありません。 。

EDIT3: はこれが働くことになった形です: <%の@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 %> 

答えて

1

それはあなたの人形やRubyの中にこれを実行しようとしている場合は不明であるので、ここでは両方の中にそれを行う方法です。

人形:前パペットtemplate機能(コメントは、この答えのために解明され、実際にテンプレートを形成する前に削除)を通過したERBで

$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

ルビー:

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

このデータは人形のものですが、私はerbで使用しようとしています。あなたが書いたものを出発点として使用して、私は上に投稿した編集(主に「dos」)を使って作業します。 – pozcircuitboy

+0

はまだその構文に満足していません。 ' - :6:構文エラー、予期しない '、'、入力の終了を期待しています ; @hash ['datacenter1']。それぞれ| cage_key、c​​age_values | do carrotがcage_keyとcage_valuesを分けるスペースにあります – pozcircuitboy

+0

テンプレート .erbを7行目で解析できませんでした。行7は: '<% - service_array.each do | service_element | - %> ' 詳細:未定義のメソッド' each 'for nil:NilClass' これを取得したら、各データセンター名ごとに別のループをラップすることができます。 – pozcircuitboy

関連する問題