Reputation: 715
So I am pretty green on chef and ruby. I am working have been making a cookbook to install influxdb's telegraf. I have devised a system for this recipe to generate custom configurations based on a list of attributes stored in a default attribute hash.
Now I would like to extend this so that dependent cookbooks can add to the attribute that generates the config so that I can add new configurations to the telegraf config without the telegraf config having to be responsible for the partial template config introduced by the cookbook using it. here is the approach.
in my telegraf cookbook I have default attribute like so
default['telegraf']['config']['partials'] = [
{
variables: { hostname: "hostname" },
templateName: 'output-win-perf-influxdb.erb',
},
{
variables: {},
templateName: 'input-win-perf-statsd.erb',
},
{
variables: {},
templateName: 'input-win-perf-system.erb',
}
]
and which is used in this template resource
template 'C:\\Program Files\\telegraf\\telegraf.conf' do
source 'telegraf/telegraf.conf.erb'
action :create
variables (node.default['telegraf']['config'])
end
The partials get rendered into telegraf.conf with
<% @partials.each do |partial| %>
<%= render "telegraf/partials/#{partial['templateName']}", :variables => partial['variables']%>
<% end %>
Now to test how this extends to dependent cookbooks I created a new cookbook that depends on win-telegraf
. In the new cookbook I attempted to add to the list of partials
like so
default['telegraf']['config']['partials'].push(
{
variables: { environments: ["chi", "main"] },
templateName: 'test.erb',
}
)
I kinda expected this to fail because it wouldnt be able to find the .erb for the new partial template. But looking at the run log it doesnt even appear that the new item was added to the array. I went with an array to maintain order, but might have to take a different approach if this is not possible.
Upvotes: 0
Views: 1635
Reputation: 54267
Check out https://coderanger.net/arrays-and-chef/ for the full version but tl;dr this gets unmanageable really fast. Use a hash instead, even if you throw away the keys (though you could use the key as the template name here, probably). That allows normal deep-merge logic to save you from a lot of pain.
Upvotes: 1