27
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Git] 鍵などの秘匿情報をgitに上げない為のスクリプトを全プロジェクトに適用させる

Last updated at Posted at 2015-12-24

初心者がAWSに手を出して$6,000請求されて、泣きそうになったお話。を読んで、わたしもきっとやるだろうなぁと思い、とりあえず自動でチェックしてもらうスクリプトだけでも入れておこうと思いました。

1. Git Templates

$ git config --global init.templatedir '~/.git-templates'

これによって各プロジェクトの.git/以下に~/.git-templates以下のファイルがコピられます。git initしたときに。

2. Global Hooksの為のディレクトリ作成

$ mkdir -p ~/.git-templates/hooks

3. ~/.git-templates/hooks/以下にコードを書きます。

pre-commit
#!/bin/sh

if git rev-parse --verify HEAD >/dev/null 2>&1
then
    against=HEAD
else
    # Initial commit: diff against an empty tree object
    EMPTY_TREE=$(git hash-object -t tree /dev/null)
    against=$EMPTY_TREE
fi

# Redirect output to stderr.
exec 1>&2
 
# Check changed files for an AWS keys
FILES=$(git diff --cached --name-only $against)

if [ -n "$FILES" ]; then
    KEY_ID=$(grep -E --line-number '[^A-Z0-9][A-Z0-9]{20}[^A-Z0-9]' $FILES)
    KEY=$(grep -E --line-number '[^A-Za-z0-9/+=][A-Za-z0-9/+=]{40}[^A-Za-z0-9/+=]' $FILES)

    if [ -n "$KEY_ID" ] || [ -n "$KEY" ]; then
        exec < /dev/tty # Capture input
        echo "=========== Possible AWS Access Key IDs ==========="
        echo "${KEY_ID}"
        echo ""

        echo "=========== Possible AWS Secret Access Keys ==========="
        echo "${KEY}"
        echo ""

        while true; do
            read -p "[AWS Key Check] Possible AWS keys found. Commit files anyway? (y/N) " yn
            if [ "$yn" = "" ]; then
                yn='N'
            fi
            case $yn in
                [Yy] ) exit 0;;
                [Nn] ) exit 1;;
                * ) echo "Please answer y or n for yes or no.";;
            esac
        done
        exec <&- # Release input
    fi
fi

# Normal exit
exit 0

4. 実行可能にする

$ chmod a+x ~/.git-templates/hooks/pre-commit

5. 上記を対応させたいプロジェクトでgit initします。

{project_root}
$ git init

https://coderwall.com/p/jp7d5q/create-a-global-git-commit-hook
https://gist.github.com/DmZ/3a99d829f17af383712b

27
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
27
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?