Take the 2-minute tour ×
Server Fault is a question and answer site for professional system and network administrators. It's 100% free, no registration required.

I have a recipe with multiple calls to a given resource, let's say directory. The calls to directory, for the most part, have very similar parameters (i.e. same owner, same action, etc.) - i.e. a lot of duplication. However, there is a particular parameter that changes frequently, namely the mode.

My goal is to reduce the duplication in my recipes and create something of a convenience method.

I'm leaning towards creating a library with a method like this:

def apply_directory_rule(path, mode_num)
  directory path do
    owner "something"
    group "something_else"
    mode mode_num
    action :create
  end
end

Then, in the recipe, each time I wanted to create a directory for the applications, I would simply call the following:

applications.each do |application|
  apply_directory_rule "#{application}/shared", 0755
end

I have not been able to test this yet, but I guess my main question is whether or not Resources, in this case directory are available like this in libraries? Secondarily, I'm not convinced this is the best pattern - any suggestions to reduce this duplication in my recipes is appreciated!

share|improve this question

1 Answer 1

up vote 0 down vote accepted

You can simply define a method in a recipe, and use it in that recipe. It's simple and gets the job done.

If you need to reuse the pattern in different recipes, or just want to use more "Chef-y" approach, there are two tools specifically for this.

In simple cases, you can use definitions; more complex situations require writing your own lightweight resource and provider (LWRP). Both are usable in other recipes and in other cookbooks.

You can read a good writeup on creating LWRPs here: http://dougireton.com/blog/2012/12/31/creating-an-lwrp/, http://dougireton.com/blog/2013/01/07/creating-an-lwrp-part-2/, http://dougireton.com/blog/2013/01/13/creating-an-lwrp-part-3/.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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