Using the New “load_recipe” Chef Function with Shef

If you are developing chef recipes it really helps to use the command line tool called shef. Shef is just a REPL to run chef in an interactive ruby session. If you haven’t ever tried it, you can find some nice instructions over here to get you going.

Shef gives an easy way to iterate on your recipes so that you can make small changes and see the effects. However, I found the _includerecipe function would only load the recipe one time, and complain that its seen the recipe before on subsequent tries. I added a small patch that implemented a new function called _loadrecipe that will allow you to reimport the recipe. The problem is that once the recipe is loaded again, the resource list is reimported giving us the same set of resources twice.

You can see the list of resources that are loaded up like so

chef:recipe > puts run_context.resource_collection.all_resources
package[php]
package[php-common]

If you were to call _loadrecipe again the list would double, and the new code would be run second when calling _runchef

chef:recipe > puts run_context.resource_collection.all_resources
package[php]
package[php-common]
package[php]
package[php-common]

The trick is that you can clear this list with this command

run_context.resource_collection = Chef::ResourceCollection.new

So to use _loadrecipe you should call the above before it to clear the current list. This can be done in one line like so

run_context.resource_collection = Chef::ResourceCollection.new; load_recipe "php"

Hopefully I’ll be able to patch things to add a _reloadrecipe that overwrites the old resources so you don’t have to use this trick, but for now this will work to get quick iterations going.