Note from the publisher: You have managed to find some of our old content and it may be outdated and/or incorrect. Try searching in our docs or on the blog for current information.

CircleCI 2.0 ushered in a new era for continuous integration and delivery. Among the new features in 2.0 (including a new configuration file format, an emphasis on Docker images, and Workflows) came the ability to build locally via the CircleCI CLI. We can use local builds together with Git to validate our config file on EVERY COMMIT, effortlessly.

The CircleCI CLI is great for troubleshooting problem builds via building locally and provided as an alternative to running SSH enabled builds.

The focus of this post will be on the CLI’s validation feature.

The Problem

Have you ever commited some changes, pushed them up to GitHub, and had a CircleCI build run for about 3 seconds before failing? This could be due to something simple, like a stray TAB character that was lurking on line 7 instead of the normal 2-space indent.

When there are several tiny errors like that in your config file, there can be a loop of “fix, commit, push, fail, start over” that goes on for several minutes. That might be acceptable when working on meaty features in code, but not config syntax.

Building locally can validate your configuration with a single line: circleci config validate -c .circleci/config.yml . With a quick Git hook, we can even automate that.

The Solution

We’re going to run the validate command in a git pre-commit hook in order to make sure our configuration file is working as expected (typically .circleci/config.yml ).

First, make sure you have the build tool installed on your local machine. Instructions are available in CircleCI docs. Next, you’ll want to create the following file in your repo’s .git directory to create the Git hook. This can be done with: vim .git/hooks/pre-commit . If you’re not using vim , replace with nano or whichever editor you like using. Feel good about yourself for automating part of your automation system.

The Git hook:

#!/usr/bin/env bash # The following line is needed by the CircleCI Local Build Tool (due to Docker interactivity) exec < /dev/tty # If validation fails, tell Git to stop and provide error message. Otherwise, continue. if ! eMSG = $( circleci config validate -c .circleci/config.yml ) ; then echo "CircleCI Configuration Failed Validation." echo $eMSG exit 1 fi

And that’s it. Once the git hook Bash script is placed correctly in your repository, the build tool in the CLI will validate your config before every commit. If it’s valid, your commit will proceed as usual. If not, you’ll see error message(s) and the commit will be cancelled.

More Information