はじめに
現在個人用、会社用、顧客用で3つのgithubアカウントを行ったり来たりしてます
うっかり別アカウントの名前でCommitしちゃたりしていたりするのでどうにかしたかった
やりたいこと
- ディレクトリ毎にgit clone、git pull、git pushする際のユーザを固定したい(使うssh鍵を固定したい)
- ディレクトリ毎にgit commitする際のユーザを固定したい(git configを固定したい)
いいやりかたないかなーって調べたらけどこれはマッチしなかった
~/.ssh/configに
Host accountA.github.com
User git
HostName github.com
IdentityFile ~/.ssh/accountA_github_rsa
Host accountB.github.com
User git
HostName github.com
IdentityFile ~/.ssh/accountB_github_rsa
って書いて、git cloneするときに
git clone git@accountA.github.com:accountA/repositoryName.git
って書くやり方はみかけたんだけどcloneするときにHost名書き換えするのめんどっちくない?って思った
前提
環境
OS:macOS 14.3.1
多分どのOSでもちょびっと変えれば動くと思いますが検証してないんでがんばって
アカウントごとにrepositoryはディレクトリ分けしていることが条件です
まずはディレクトリ分けしてるよね?って確認
アカウントAのrepositoryをcloneしているディレクトリ
~/github/accountA
アカウントBのrepositoryをcloneしているディレクトリ
~/github/accountB
ディレクトリ毎にgit clone、git pull、git pushする際のユーザを固定したい(使うssh鍵を固定したい)
ssh configに追記
~/.ssh/config
# git
Host github.com
User git
HostName github.com
Match Host github.com Exec "pwd | grep accountA"
IdentityFile ~/.ssh/accountA_github_rsa
Match Host github.com Exec "pwd | grep accountB"
IdentityFile ~/.ssh/accountB_github_rsa
※Match文は次のMatchが来るか、ファイルの末尾がくるまで続くみたいなのでファイルの最終行に書くとよいです
上記の最後にMatch all を書いてもよいらしい。その後にも続きをかけるようになるとのこと。
これってなにしてるの?
Match Host github.com Exec "pwd | grep accountA"
上記は
Hostが github.com
かつ、 pwd | grep accountA
を実行した結果戻り値が 真(True)
だったら
IdentityFile ~/.ssh/accountA_github_rsa
を使うよって書いてあります
~/github/accountA/
で Repositoryをcloneする場合のコマンドはgit clone git@github.com:accountA/test_repo.git
って感じになると思いますが、hostは github.com
だし、実行ディレクトリで pwd | grep accountA
したら true
なのでaccontA用の秘密鍵を使用して認証を行う
※accountAの中にaccountBの名前を含むdir名が含まれてたりすると駄目になると思うので、そこは気をつけて
もしそういう自体が想定されるときはgrepの条件を accountA
ではなく github/accountA
とかにしてもいいかも。
ディレクトリ毎にgit commitする際のユーザを固定したい(git configを固定したい)
config情報を書き換える準備
.gitconfig_dirを作成する
mkdir ~/.gitconfig_dir
アカウント毎にconfigファイルを用意する
gitconfig_accountA
[user]
email = hosoi.toru@accountA.co.jp
name = hosoi
gitconfig_accountB
[user]
email = toru@accountB.com
name = toru
.gitconfigに追記
~/.gitconfig
[credential]
helper = !aws codecommit credential-helper $@
UseHttpPath = true
[user]
email = toru@hosoi.jp
name = thorhosoi
[includeIF "gitdir:~/github/accountA/"]
path = ~/.gitconfig_dir/gitconfig_accountA
[includeIF "gitdir:~/github/accountB/"]
path = ~/.gitconfig_dir/gitconfig_accountB
おしえてください
複数アカウント使っている場合に切り替えってどうしてます?
もっといい切替方法あったら教えてください
ちなみに
githubでは無料アカウントの複数所持はだめですよって言ってるので、どっちかは有料アカウントですよね?
https://docs.github.com/ja/site-policy/github-terms/github-terms-of-service#b-account-terms
1 人の個人または 1 法人が維持できる無料アカウントは 1 つのみです (マシン アカウントを管理することを選択することもできますが、アカウントはマシンを実行するためにのみ使用できます)。