Opscode
Home     Introduction to Chef     Cookbooks     Blog     GitHub     Tickets 

Libraries

Libraries allow you to include arbitrary Ruby code, either to extend Chef's language or to implement your own classes directly. They are the secret sauce that will allow you to plug in to your existing infrastructure and utilize it to inform how your systems are configured.

Libraries are defined in your_cookbook/libraries/library_name.rb. Any libraries you include in a Cookbook will automatically be required, and available within all your Recipes, Attribute Files and Definitions. What this means is that the library files will automatically be read - however you may need to do something else to actually use them, depending on their contents.

Here's a simple example, showing how you'd use module defined in a Library in your recipe:

your_cookbook/libraries/your_example_library.rb
your_cookbook/recipes/default.rb

Basic Libraries

Lets say you have a customer record you are storing in an attribute file, that looks like this:

A customer attribute file

In a recipe, you could say:

Simple recipe

But that feels verbose, and you are going to do it all the time. You would rather say:

Advanced recipe

You could achieve that with a simple library, like this:

Library to extend Chef::Recipe

Lets say you wanted some code to easily loop over every customer, like this:

Loop over customers

You could have a library like this:

Loop over customers

Advanced Library Usage

You can also use Libraries to connect up to databases, talk to LDAP, or do anything else you can do with Ruby.. which is basically anything.

If you are going to go too crazy, consider putting your libraries in a new namespace, and calling them directly from your Chef Recipes - that way, we won't have too much pollution of the Chef::Recipe namespace.

Here is an example of connecting to a database and returning a list of customer Virtual Hosts.

Virtual Hosts from a Database
This rocking example..

Was provided by Arjuna (fujin). He's awesome.

You could then use this in a recipe like so:

Using ISP.vhosts in a Recipe
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.

Copyright © 2009 Opscode, Inc. All Rights Reserved.