Skip to content

Instantly share code, notes, and snippets.

@drocamor
Created April 23, 2013 16:21
Show Gist options
  • Save drocamor/5445057 to your computer and use it in GitHub Desktop.
Save drocamor/5445057 to your computer and use it in GitHub Desktop.
A pre-commit git hook that will make sure CloudFormation templates have had their JSON cleaned up. Really helps with merging and diffing of CloudFormation templates.
#!/bin/bash
#
# git pre-commit hook to make sure you are commiting properly formatted CloudFormation code
# This should go in .git/hooks/pre-commit in a repo with CFN templates.
if git-rev-parse --verify HEAD >/dev/null 2>&1; then
against=HEAD
else
against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi
# This assumes your CloudFormation templates end in .template
for filename in `git diff-index --name-status $against -- | cut -c3-` ; do
if [[ $filename =~ .*\.template ]]
then
# Make a temporary file with properly formatted JSON.
tempfile=`mktemp /tmp/json-validator.XXXXX`
python -mjson.tool $filename > $tempfile
# Are the files different?
diff $filename $tempfile > /dev/null 2>&1
if [ $? -eq 0 ]
then
# If no, just remove the temp file and move on.
rm $tempfile
else
# Files are different. You can't commit.
rm $tempfile
echo "You may not commit."
echo "The JSON in file $filename is not formatted properly."
echo "Use python -mjson.tool to fix this before committing."
exit 1
fi
fi
done
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment