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.


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

  • Although it was not a real part of your question, just to set you on the right path in chef-land, within a LWRP (re:'Providers') I think the object you are looking for is 'current_resource' method which returns a reference to the current resource object, not 'load_current_resource' method which does other things. docs here: docs.opscode.com/lwrp_custom_provider.html#current-resource – Gregory Patmore Jul 7 '14 at 14:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.