Overriding Cookbook Templates

This post shows how to customize community Chef cookbooks using wrapper cookbooks without editing upstream code directly. It demonstrates a resource override pattern for templates that keeps upgrades easier and safer.

Coveros Staff

October 28, 2014

As a general practice when using community cookbooks I try not to, unless absolutely necessary, update the code in the cookbook.  This makes updating the version of the cookbook in your git repository to the latest and greatest a bit easier.  Sometimes the community cookbook does not behave exactly the way I want it to behave.

To get around these issues I use wrapper cookbooks to add in the features or changes I need.  In the wrapper cookbook, the code below will override a template already declared in the community cookbook.

include\_recipe "community\_cookbook"

begin
  override = resources(:template => "/etc/init.d/run\_script")
  override.cookbook "wrapper\_cookbook"
rescue Chef::Exceptions:ResourceNotFound
  Chef::Log.warn "template not found
end

The template file will need to exist in the templates directory of the wrapper cookbook. The metadata.rb file for the wrapper cookbook also needs to be modified to include a dependency for the community cookbook.

Coveros Staff

Coveros Staff

This post represents the collective insights of the Coveros team. Our staff consists of software experts who bring deep experience in secure agile development, DevOps, testing, and software quality. Over the past 20 years, Coveros has trained more than 30,000 professionals and worked with half of the Fortune 100 companies on mission-critical software development challenges. We draw on this extensive experience to share practical insights, proven strategies, and real-world solutions that help organizations build better software faster and more securely.