From: https://dev.to/rizkyzhang/setup-multiple-ssh-keys-for-multiple-github-accounts-393l
ssh-keygen -t rsa -f ~/.ssh/id_rsa_fulltime -C "[email protected]"
ssh-keygen -t rsa -f ~/.ssh/id_rsa_portfolio -C "[email protected]"
ssh-add ~/.ssh/id_rsa_fulltime
ssh-add ~/.ssh/id_rsa_portfolio
Now you need to go to ~/.ssh and create a file named config inside it. Open it with vim or other text editor and add the following configurations.
Host *
AddKeysToAgent yes
IdentitiesOnly yes
Host github.com-fulltime
HostName github.com
IdentityFile ~/.ssh/id_rsa_fulltime
Host github.com-portfolio
HostName github.com
IdentityFile ~/.ssh/id_rsa_portfolio
Host * means the config will be applied to every host, not only github.com-prefix.
AddKeysToAgent
tells SSH to remember your passphrase, so you don't need to enter it every time, only on every new login session.
IdentitiesOnly
is the gotcha I mean earlier. Let's say you are currently authenticated with fulltime account, and you want to switch to personal account. If you did not specify it, SSH will continue to use the first authenticated SSH key even though we have already specified different SSH key for each account, in this case it will continue to use fulltime SSH key for each account.
The postfix (eg -portfolio) after github.com is used to identify different SSH keys, you can name it whatever you like but it should be unique, usually I named it the context in which the GitHub account is used for.
- Create a
.gitconfig
in the root of personal directory. - Specify email, username and identifier postfix in below format.
[user]
email = [email protected]
name = test
[url "[email protected]"]
insteadOf = [email protected]
- Create a global
.gitconfig
in your home directory to tell SSH which local .gitconfig to use for personal directory by specifying the path.
[includeif "gitdir:~/Projects/personal/"]
path = ~/Projects/personal/.gitconfig
Now try to clone a repository, SSH will automatically choose the correct SSH key.