rubychef-infrachef-recipecookbookberkshelf

Merge attributes from different Chef cookbooks or recipes


Is there a possibility to merge attributes from several cookbooks or recipes?

What I want to achieve is the following:

cookbook 1

sets a default list of attributes like default[:bamboo][:agent][:attributes] = { 'system.attr-1' => 'test1' }

in template.conf, I have

<% if @options -%>
<%   @options.sort.map do | option, value | -%>
<%= option %>=  <%= value %>
<%   end -%>
<% end -%>

cookbook 2

inherent "cookbook 1" and have 2 recipes

recipe1

   node.default[:bamboo][:agent][:attributes]                = {
       'system.attr-2'                           => 'test2'
   }

recipe2

   node.default[:bamboo][:agent][:attributes]                = {
       'system.attr-3'                           => 'test3'
   }

Now what I want is that the template.conf from "cookbook 1" is updated/merged with the attributes of cookbook2 and those recipes.

Is this possible? If not, what are the other options?


Solution

  • In cookbook 2, you want to take advantage of Ruby's Hash#merge:

    node.default[:bamboo][:agent][:attributes] = node[:bamboo][:agent][:attributes].merge(
      'system.attr-3' => 'test3'
    )
    

    And then ensure cookbook 2 depends on cookbook 1 (so the attributes are loaded first).