Search code examples
erbchef-recipecookbook

Chef Template Nested Loops


I have a small problem with my chef cookbook, i'm trying todo a nested loop (loop in loop). I have a array with multiple levels and i would like to loop all levels in a chef template. Right now i'm down at the following:

Template:

        <% @countries.each do |country| %>
                <% @countries[@country].each do |key, val| %>
                        <Publication <%= @country @key @val %> />
                <% end %>
        <% end %>

Attribute:

default['countries']['IE'] = {'57'=>'val2','58'=>'val2','61'=>'val','63'=>'val'}
default['countries']['DE'] =  {'110'=>'val2','113'=>'val2','115'=>'val2'}
default['countries']['BE'] = {'134'=>'val2','138'=>'val2','139'=>'val2'}

Recipe:

template "conf.xml" do
    action :create
    variables ({
        :countries => node['countries']
              })
end

So first i would like too loop the countries level, then loop each level in that array by using the key and val of the array. I hope someone can help me out with this one.

Best, - Thijs


Solution

  • You can do something like this,

        <% @countries.each do |country, country_details| -%>
          <% country_details.to_hash.each do |value| -%>
            <Publication <%= "#{country} #{value[0]} #{value[1]}" %> />
          <% end -%>
        <% end -%>
    

    The country_details should ideally be a hash, however, Chef changes that to something called an ImmutableMash which needs to be converted to a Hash. However, on conversion the value received after iteration is an array instead of a hash so needs to be written in the array format i.e. value[0] and value[1].

    The above code returns the following output, not sure if you're looking for this,

        <Publication IE 57 val2 />
        <Publication IE 58 val2 />
        <Publication IE 61 val />
        <Publication IE 63 val />
        <Publication DE 110 val2 />
        <Publication DE 113 val2 />
        <Publication DE 115 val2 />
        <Publication BE 134 val2 />
        <Publication BE 138 val2 />
        <Publication BE 139 val2 />