Skip to content

Instantly share code, notes, and snippets.



Last active Feb 20, 2021
What would you like to do?
Git pre-commit hook to search for Amazon AWS API keys.
if git rev-parse --verify HEAD >/dev/null 2>&1
# Initial commit: diff against an empty tree object
# Redirect output to stderr.
exec 1>&2
# Check changed files for an AWS keys
KEY_ID=$(git diff --cached --name-only -z $against | xargs -0 cat | grep -c -E '[^A-Z0-9][A-Z0-9]{20}[^A-Z0-9]')
KEY=$(git diff --cached --name-only -z $against | xargs -0 cat | grep -c -E '[^A-Za-z0-9/+=][A-Za-z0-9/+=]{40}[^A-Za-z0-9/+=]')
if [ $KEY_ID -ne 0 -o $KEY -ne 0 ]; then
echo "Please check your code and remove API keys."
exit 1
# Normal exit
exit 0

This comment has been minimized.

Copy link
Owner Author

@DmZ DmZ commented Jul 21, 2014

Must be installed into .git/hooks directory of a project.
To use for all new projects must be installed globally
(or with help of git-hooks


This comment has been minimized.

Copy link

@sadams sadams commented Apr 29, 2015

Great idea, but it's falsely matching any 40 char quoted string, which i sadly have in my repo. If i manage to successfully tweak regex will reply here.


This comment has been minimized.

Copy link

@czardoz czardoz commented Aug 10, 2015

I enhanced this script to also spit out the filename and line number where the Keys were detected:


This comment has been minimized.

Copy link

@dduvnjak dduvnjak commented Feb 10, 2016

Update to work on both Linux and OS X (uses perl instead of grep), as well as a regex pattern recommended by AWS:

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