リポジトリ単位でgitの証明書(アカウント)を分割する方法
複数のgithubアカウントがあり、それぞれ同時に開発する際にアカウントを切り替えるのが面倒だったので、リポジトリ単位で自動的に任意のアカウントを使ってgithubと通信する方法を調べたので、まとめておく。
ディレクトリ構成
- .ssh/ config # このファイルにそれぞれのアカウントの証明書の参照先/ホスト名を書く - .gitconfig # メインのgitconfig - アカウントA/ - .gitconfig - アカウントB/ - .gitconfig
.ssh/config 証明書設定
以下のように入力して、アカウント毎にid_rsa
の参照先を書く
host github-<アカウントA> HostName github.com IdentityFile ~/.ssh/id_rsa_<アカウントA> User git host github-<アカウントB> HostName github.com IdentityFile ~/.ssh/id_rsa_<アカウントB> User git
以下のようにホスト名を指定して、動作確認ができる。
# ssh -T github-<アカウントA> Hi HOGEHOGE! You've successfully authenticated, but GitHub does not provide shell access.
.gitconfig (メイン)
アカウントとリポジトリのディレクトリの対応付けをする。 アカウント単位でまずディレクトリを作成し、その中にリポジトリをクローンするとよさそう。
[includeIf "gitdir:~/volume/git/accountA/"] path = ~/volume/git/accountA/.gitconfig [includeIf "gitdir:~/volume/git/accountB/"] path = ~/volume/git/accountB/.gitconfig
実際にクローンする
後はgitクローンする際に 通常github.com
と指定しているホスト名の部分を.ssh/config
で記載したhostの値に置き換えるだけ。
git clone git@<変更したホスト名>:<リポジトリ>.git
以上。 今までアカウント切り替えをしてgit nameやemailを間違ってしまっていたが、この設定によって煩雑さが大きく解消された。