How can I use same template file for multiple recipes in same cookbook with diff params


#1

I have 1 template which is getting called my multiple recipes in same cookbook So far it was working fine but now requirement has been changed.

Few modifications have been done in .erb file and some content has been added (like buffersize and notifications.) Value for such attributes are different for different recipes.

How can I achieve this?


#2

To keep things relatively simple, you could use wrapper cookbooks for each of your slightly different use cases.
In your wrapper, have an include_recipe 'cookbook::recipe' in the default recipe, also set your attributes however you want in the attributes/default.rb of your wrapper.

You could also do the same thing with a role but using a cookbook has advantages, such as proper versioning.

If you wanted to get fancy, just write a reusable resource.


#3

Templates allow you to pass variables from the recipe into the template. It would look something like this:

recipe1.rb:


template “mytemplate” do
… // other attributes as needed
variables(
:buffersize => 32768
)
end

reciple2.rb:


template “mytemplate” do
… // other attributes as needed
variables(
:buffersize => 65536
)
end

mytemplate.erb:


buffersize = <%= @buffersize %>

A couple notes:

The round bracket following the variables key word must immediately follow - do not add a space!

The <%= %> tag in the template will output the return value of whatever is in it. If you need to instead perform logic (such as an if statement), use the <% %> syntax without the = It is plain ruby code.

Kevin Keane
The NetTech
http://www.4nettech.com
Our values: Privacy, Liberty, Justice
See https://www.4nettech.com/corp/the-nettech-values.html


#4

To suggest a slight modification to what Kevin said, you could use a node attribute in a wrapper cookbook to set the variable being passed.

In cookbook1 attributes/default.rb set a default value:

default['cookbook1']['buffersize'] = 65536 # including the cookbook name helps isolate the namespace and avoid collisions.

In your cookbook1::has_a_template recipe:

template 'mytemplate' do 
...
  variables(
    :buffersize => node['cookbook1']['buffersize']  
  )
end

Then, if you wish to set a different value for that template you can easily do so with the node attribute - in another cookbook, in a role, environment, on individual nodes. I personally suggest the wrapper cookbook method because it will be versioned and (hopefully) live in your version control. In larger environments I find that the other methods lead to “who set this node attribute”, “why did they set it” and “Why is there one value on the environment and another in this role, and a third on the server”?

–Jp Robinson