Automate All the Things!

Doug Ireton's blog about Chef, Git, Ruby, Vim, and Infrastructure Automation

Creating a Git Pre-commit Hook for Chef Cookbooks

| Comments

We’ve been using Chef in our group now for a few months, but until now we haven’t been serious about linting or testing our Chef cookbooks. I decided to get serious today and write a Git pre-commit hook for linting cookboks.

Git runs the pre-commit hook script before each commit. This allows you to run code quality checks so only clean code is committed to your repo.

It’s important to note that git hooks aren’t copied down when you clone a git repo. Each developer will need to create his or her own pre-commit hook script in the .git/hooks/ directory of the repo. If you wanted to get fancy, you could keep git hook scripts in a “utility” repo and have a rake script to copy them to the right location.

The pre-commit script below does four things:

  1. Runs a built-in Git whitespace check for trailing whitespace, mixed tabs and spaces, etc.
  2. Runs ‘knife cookbook test’ to check Ruby and ERB template syntax.
  3. Runs ‘tailor’ to check your code against Ruby style conventions.
  4. Runs , the de facto Chef cookbook linting tool.