Best practice to write a reusable recipe?


#1

I am writing a recipe like below. The “template” resource is only used for some scenarios but service resource is quite common and used in all scenarios.

{code}
template “/opt/splunk/etc/system/local/server.conf” do
notifies :restart, ‘service[splunk]’, :delayed
end

service ‘splunk’ do
supports status: true, restart: true, reload: true
action :nothing
end
{code}

What is the best practice to reuse “service” resource and meanwhile, also have flexibility to use “template” resource according to the scenario? There seems to be several options
a) create a flag variable, and add a “only_if” line in “template” block to check the flag variable, then determine to run “template” or not.
b) take “service” out and put it into a new common recipe. The recipe which has needs to restart service would use “include_recipe” to reuse “service” resource.
c) put “template” and “service” into different recipes. The top recipe uses “include_recipe” to add one of them, or both of them in. But it may lead to problem that how to make “template” in a recipe manage to notify “service” in another recipe.

Any advice about it?


#2

Daniel,

a) an only_if guard is precisely what you would use
b and c) there is no need to worry about moving these to different recipes because of how resources work inherently. Once a node has a given run_list, it expands it, and then creates what we call the Resource Collection. Any resource can notify any other resource in the resource collection so it does not matter what recipes the resources are in so long as they were declared somewhere by one of the recipes in the run_list.

Hopefully that clears this up a bit more,