git-crypt でリポジトリ内の機密ファイルを透過的に暗号化する
Git リポジトリに設定ファイルをコミットしたいが、機密情報(パスワード、SSH キー、API トークンなど)が含まれている場合、git-crypt を使うと透過的に暗号化できる。
git-crypt とは
git-crypt は Git リポジトリ内の特定ファイルを自動的に暗号化するツール。
- commit 時: 自動的に暗号化されてリポジトリに保存
- checkout 時: 自動的に復号化されてワーキングディレクトリに展開
- GitHub 上: 暗号化されたバイナリとして表示
一度設定すれば、通常の git 操作と同じように使える。
インストール
# Ubuntu/Debian sudo apt install git-crypt # macOS brew install git-crypt セットアップ(キーファイル方式)
GPG キーを使う方法もあるが、個人利用ならキーファイル方式がシンプル。
1. 初期化
cd your-repo git-crypt init 2. 暗号化対象を指定
.gitattributes に暗号化したいファイルパターンを追加:
# 特定のプレフィックスを持つファイルを暗号化 echo 'gitcrypt_* filter=git-crypt diff=git-crypt' >> .gitattributes # または特定ディレクトリ echo 'secrets/** filter=git-crypt diff=git-crypt' >> .gitattributes 3. キーファイルをエクスポート
# キーファイルを安全な場所に保存 git-crypt export-key ~/.git-crypt-key # このファイルは絶対にリポジトリにコミットしない # バックアップは USB やパスワードマネージャーに保存 4. コミット
git add .gitattributes git add gitcrypt_secret-config.xml git commit -m "chore: add encrypted config" 別のマシンで復号化
git clone your-repo cd your-repo # キーファイルで復号化 git-crypt unlock ~/.git-crypt-key 暗号化状態の確認
git-crypt status 出力例:
encrypted: ansible/backups/omv/gitcrypt_config.xml not encrypted: README.md not encrypted: .gitattributes ファイル命名規則のすすめ
暗号化対象を明示的にするため、ファイル名にプレフィックスを付けると分かりやすい:
gitcrypt_* # git-crypt で暗号化 secrets/ # 機密情報ディレクトリ *.secret.yml # 機密設定ファイル 注意点
- キーファイルの管理: 紛失すると復号化できなくなる
- 既存の履歴: git-crypt は新規コミットのみ暗号化。既存の履歴は書き換えが必要
- マージコンフリクト: 暗号化ファイルのコンフリクト解決は難しい
ansible-vault との比較
| 項目 | git-crypt | ansible-vault |
|---|---|---|
| 透過性 | 完全に透過的 | 手動で encrypt/decrypt |
| 対象 | 任意のファイル | YAML/テキスト |
| 統合 | Git フィルター | Ansible 組み込み |
| 用途 | 汎用 | Ansible 特化 |
Ansible プロジェクトでも、ansible-vault より git-crypt の方がシンプルな場合がある。
参考
- git-crypt GitHub
- スター 9,500+、活発にメンテナンスされている
This post is licensed under CC BY 4.0 by the author.