Skip to content

Instantly share code, notes, and snippets.

@tmepple
Forked from ralovely/pre-commit.example
Last active February 3, 2018 22:11
Show Gist options
  • Save tmepple/1b8a73cba052d3b8aab5a333f12b689a to your computer and use it in GitHub Desktop.
Save tmepple/1b8a73cba052d3b8aab5a333f12b689a to your computer and use it in GitHub Desktop.
Git pre-commit hook for Ansible Vault
#!/bin/sh
#
# Pre-commit hook that verifies if all files containing 'vault' in the name
# are encrypted.
# If not, commit will fail with an error message
#
# File should be .git/hooks/pre-commit and executable
FILES_PATTERN='.*vault.*\.yml$'
REQUIRED='ANSIBLE_VAULT'
EXIT_STATUS=0
wipe="\033[1m\033[0m"
yellow='\033[1;33m'
# carriage return hack. Leave it on 2 lines.
cr='
'
for f in $(git diff --cached --name-only --diff-filter=d | grep -E $FILES_PATTERN)
do
MATCH=`grep --invert-match --no-messages $REQUIRED $f | head -n1`
if [ -z $MATCH ] ; then
UNENCRYPTED_FILES="$f$cr$UNENCRYPTED_FILES"
EXIT_STATUS=1
fi
done
if [ $EXIT_STATUS = 0 ] ; then
exit 0
else
echo '# COMMIT REJECTED'
echo '# Looks like unencrypted ansible-vault files are part of the commit:'
echo '#'
while read -r line; do
if [ -n "$line" ]; then
echo "#\t${yellow}unencrypted: $line${wipe}"
fi
done <<< "$UNENCRYPTED_FILES"
echo '#'
echo "# Please encrypt them with 'ansible-vault encrypt <file>'"
echo "# (or force the commit with '--no-verify')."
exit $EXIT_STATUS
fi
@tmepple
Copy link
Author

tmepple commented Feb 16, 2017

With the previous version of the script if wouldn't let me commit deleted .vault files. Adding --diff-filter=d to the git diff call excludes any deleted files from the list of files to be checked for the magic header text and works great. Just wanting to add this in case it helps anyone.

@bmyrtil
Copy link

bmyrtil commented Feb 3, 2018

Helped. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment