新規案件を始めるにあたり、1台のPCで複数のGithubアカウントを使い分ける必要があったので、その備忘録です。
Githubでは、1人が複数の無料アカウントを保持することは禁止されています。ご注意ください。
SSHキーを作成
ssh-keygen -t rsa
コマンドを使用して、それぞれのGithubアカウントに登録するSSHキーを作成します。
コマンドの詳しい使い方はググるとして、次のようにSSHキーを作成します。
id_foo_rsa
id_foo_rsa.pub
id_bar_rsa
id_bar_rsa.pub
作成したキーをそれぞれGithubに登録しておきます。
~/.ssh/config の設定
~/.ssh/config
を以下のように設定します。
Host foo.github.com
HostName github.com
IdentityFile ~/.ssh/id_foo_rsa
User git
Host bar.github.com
HostName github.com
IdentityFile ~/.ssh/id_bar_rsa
User git
設定後、以下のコマンドで接続確認します。
ssh -T git@foo.github.com
ssh -T git@bar.github.com
.gitconfig の設定
~/workspace/bar/**
ディレクトリ配下のプロジェクトで bar.github.com
を使用するための設定をします。
まず ~/.gitconfig.bar
を作成して bar.github.com
で使用する情報を記載します。
[user]
name = bar-name
email = bar@example.com
次に ~/.gitconfig
を次のように編集します。
[user]
name = foo-name
email = foo@example.com
[includeIf "gitdir:~/workspace/bar/**"]
path = .gitconfig.bar
設定後、以下のコマンドで確認します。
git config --get user.name
bar.github.com
の方は、対象のディレクトリ配下で何かしらの操作を行った後、確認します。
リモート接続時
リモートに接続する際には、次のようにします。
# 普通はこれでいいけど、今回はダメです。
git@github.com:<アカウント名>/<リポジトリ名>.git
# このようにする
git@foo.github.com:<アカウント名>/<リポジトリ名>.git
謝辞
勉強になりました。ありがとうございます。
https://zenn.dev/m10maeda/articles/how-to-use-multiple-git-accounts
https://zenn.dev/taichifukumoto/articles/how-to-use-multiple-github-accounts