Skip to content

Instantly share code, notes, and snippets.

@arekbartnik
Last active September 25, 2023 14:03
Show Gist options
  • Save arekbartnik/75af8f2d57a2ecccf35aa762158adf7e to your computer and use it in GitHub Desktop.
Save arekbartnik/75af8f2d57a2ecccf35aa762158adf7e to your computer and use it in GitHub Desktop.
Setup Multiple SSH Keys for Multiple GitHub Accounts

Setup Multiple SSH Keys for Multiple GitHub Accounts

From: https://dev.to/rizkyzhang/setup-multiple-ssh-keys-for-multiple-github-accounts-393l

Creating SSH keys

ssh-keygen -t rsa -f ~/.ssh/id_rsa_fulltime -C "[email protected]"
ssh-keygen -t rsa -f ~/.ssh/id_rsa_portfolio -C "[email protected]"

Adding SSH Keys Into SSH Authentication Agent

ssh-add ~/.ssh/id_rsa_fulltime
ssh-add ~/.ssh/id_rsa_portfolio

Creating SSH Config File

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.

Complete SSH keys automation

  1. Create a .gitconfig in the root of personal directory.
  2. Specify email, username and identifier postfix in below format.
[user]
  email = [email protected]
  name = test

[url "[email protected]"]
  insteadOf = [email protected]
  1. 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment