Reusable piece of code in Chef to be used several times in recipe(s)

best practiceschef

I need to reuse some scenario in my cookbooks – create several users on a single machine and install same software for each of them. Installing the software is a repeating operation which I'd like to put in a single place and reuse.

I've looked at Providers, but they seem to have a method load_current_resource which loads the current state of the system, I cannot have such a method because some users might have installed this software, others – haven't and if Chef invokes this method behind the scene, I won't have control over what particular user I'm working with at the moment.

I've also looked at MySQL Cookbook which puts some custom code into libraries folder. This might be the best option for me, but I don't know whether it's a Chef way or not.

So the question is – what is The Chef Way of putting such reusable parts of code to be used several times by the same recipe or by several of them.

Best Answer

In Chef there's a few tools techniques you can use to accomplish this, however, I think that the solution you're looking for isn't code/syntax based. I think here you want to encapsulate the repeatable code within one or more recipes (if more then one then group them within a role). Next for all the install calls leverage the common not_if/only_if clauses to install only under certain conditions.

Docs: http://docs.opscode.com/resource_common.html

Another way to do it that is slightly more painful but provides a cleaner source code tree is to leverage data bags. set up the simple json structured data bags for each user you want to install for, then in your recipe loop through the items in the data bag and apply your logic.

Docs: http://docs.opscode.com/dsl_recipe_method_data_bag.html

Related Topic