13

I would like to share a small handful of methods across recipes in a chef repo. I know that on a cookbook level I can put code in modules in the libraries directory (see related question). What I'm looking for is something like that but available across all of the cookbooks in my Chef repo.

I can think of a couple solutions:

  • Create a gem, install the gem as part of the chef run. This seems like overkill.
  • Put the file in some folder and add that folder to the $LOAD_PATH in the recipe file. I have a feeling that won't work with actual deployment because the chef server doesn't know anything about the repo.
  • Put the file in some folder and symlink that into the libraries directory of each cookbook.

The last option seems like the most viable. Is there a better/more idiomatic way to do what I want?

Community
  • 1
  • 1
dantswain
  • 5,427
  • 1
  • 29
  • 37
  • When you say "methods" are you referring to pure Ruby code, or is it code that uses Chef's DSL that could be placed in recipes? If it's pure Ruby, then a gem might be the best way out, and unless you have only a few lines of code, I hardly see it as overkill. If it's Chef code, create a library cookbook with LWRPs and include it in your top-level application cookbooks. This second approach might work for pure Ruby libraries, but I haven't tried it to be sure. – cassianoleal Jun 28 '13 at 02:01
  • 1
    It's mainly pure Ruby code. Maybe a dozen utility methods. I'm not super familiar with Chef's dependency management, but I wonder if it would work to create a cookbook that just has the shared code in its libraries folder. – dantswain Jun 28 '13 at 12:10
  • I've just tried it and it doesn't seem to work, at least not straight away. I still think that the gem path might be the best. :) – cassianoleal Jun 28 '13 at 12:49
  • Also, depending on your use case, you could create LWRPs or definitions as interfaces to your methods. This way when you include this lib cookbook as a dependency of another, you'll have those resources available for use in recipes. – cassianoleal Jun 29 '13 at 01:52

2 Answers2

21

You can use a library defined function from another cookbook but you must teach Chef that your cookbook depends on the providing cookbook.

So, for example, if in cookbook A, you have a libraries/default.rb that provides some function f, you can access it from cookbook B so long as B's metadata.rb file includes the line:

depends "A"

See the Chef documentation on metadata and libraries for more details.

Roger Lipscombe
  • 89,048
  • 55
  • 235
  • 380
Emil Sit
  • 22,894
  • 7
  • 53
  • 75
1

There are 3 distinct options allowing for sharing code in form of either chef resource (1. LWRP, 2. HWRP) or methods (3. "libraries"). I'd suggest you consider LWRPs first. I find this answer very good in explaining differences between mentioned techniques.

Community
  • 1
  • 1
riemann
  • 435
  • 4
  • 12