会社と個人でgithubアクセスを分ける

前提

既に会社用のkeyがある状態

個人用のssh private keyを作る

ssh-keygen -t ecdsa -b 256 -C {個人メールアドレス} -f {作成する鍵の名前}

作成する鍵の名前は、既にあるものと同じものを使用すると、上書きされるため注意する

ssh設定(~/.ssh/config)ファイルの編集

~/.ssh/config がない場合は作成する

Host github.com # 会社アカウント
  HostName github.com
  User git
  Port 22
  IdentityFile ~/.ssh/id_ecdsa  # 会社アカウント用の鍵
  TCPKeepAlive yes
  IdentitiesOnly yes

Host github.com.private # 個人アカウント
  HostName github.com
  User git
  Port 22
  IdentityFile ~/.ssh/id_ecdsa_personal  # 個人アカウント用の鍵
  TCPKeepAlive yes
  IdentitiesOnly yes

Githubに公開鍵を登録する

ssh接続確認

ssh -T git@github.com
ssh -T git@github.com.private

以下のメッセージが返ってくることを確認する

Hi {yourname}! You've successfully authenticated, but GitHub does not provide shell access.

ディレクトリ毎にgit設定を切り替える

~/.gitconfig は以下のような値

[user]
        name = company-user
        email = company-user@example.com
[includeIf "gitdir:~/src/github.com/personal/"]
        path = ~/src/github.com/personal/.gitconfig

~/src/github.com/personal/ の場合は~/src/github.com/personal/.gitconfig を読み込むとする

~/src/github.com/personal/.gitconfig は以下のようなものになっている

[user]
        name = personal-user
        email = personal-user@example.com

clone する

メインアカウント

git clone git@github.com:username/repository-name.git

個人アカウント

git clone git@github.com.private:username/repository-name.git

確認する

git config remote.origin.url

ghq を使うと

ghq get github.com.private:username/repository-name

/ghqroot/github.com.private/repository-name ができた。 こっちもincludeした方が良さそう

Ref

qiita.com