Query on chef template files adding in content based on recipe

210 views Asked by At

Got a query about using Chef templates.

Is it possible to update a template based on which recipe is being used. An example is that I have a collectd default recipe and a rabbitmq one that gets called. The rabbitmq part will still use parts of the default/base recipe and I only want to add data to the template if the rabbitmq bit is being called (IE collectd::rabbitmq).

Is there anyway to customise the base template based on what recipe is being used?

Cheers!

2

There are 2 answers

2
Tejay Cardon On

Yep, just use template attributes. Something like this:

template 'my template' do
  source 'some_teplate.erb'
  attributes :rabbit_stuff => true,
             :other_thing => 'somevalue'
end

And the template

....
<% if @rabbit_stuff -%>
  rabbit things in here
<% end -%>
Common stuff
....

And it doesn't just need to be a flag. You could just have lots of attributes, and do something like this based on which ones are defined.

<%= @some_attribute %> <% if @some_attribute %>
0
lamont On

If you have one template resource you can gather attributes from many cookbooks. You can use collectd/attributes/default.rb to set attributes on default['rabbitmq']['whatever'] which is then rendered by the rabbitmq cookbook into the template. If the collectd cookbook is not in the run list of the node then the cookbook will not be sync'd to the node and the attribute file will not be evaluated.

Note that if any collectd cookbook recipe appears on the node then all the files in the attributes directory are evaluated. You have to structure your cookbooks so that different roles have different cookbooks if you do this -- which may mean that you need a collectd_rabbitmq cookbook instead of a collectd::rabbitmq recipe.

That would be my first choice in how to inject different information from different cookbooks into one template resource.