0

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!

kries
  • 5
  • 1
  • 3

1 Answers1

0

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/.