Brett Tolbert
Brett Tolbert's Blog

Brett Tolbert's Blog

Using multiple SSH keys for different GitHub accounts

Brett Tolbert's photo
Brett Tolbert
·Jan 9, 2022·

2 min read

Consider that these are the normal steps to add a new repo to github:

echo "# anotherproject" >> README.md
git init
git add README.md
git commit -m "first commit"
git branch -M main
git remote add origin git@github.com:anotheraccount/anotherproject.git
git push -u origin main

But let's assume you just created another GitHub account (anotheraccount) and will be using it for the first time, adding new repo anotherproject.

First we need to create a new SSH key and add it to anotheraccount. GitHub won't allow you to associate a single SSH key with multiple accounts so you will not be able to use your existing SSH key, assuming you've already added it to your existing GitHub account (bretttolbert in my case). You must create another SSH key for anotheraccount. But how will Git know which one to use? Keep reading to find out...

Change to the ssh directory

$ cd ~/.ssh

Generate a new ssh key using email associated with second github account

~/.ssh$ ssh-keygen -t ed25519 -C "anotheraccount@gmail.com"

When prompted, give it the name id_ed25519_anotheraccount. Do not use the default name (id_ed25519) or you'll overwrite your existing SSH key. Now you should have two public/private SSH key pairs:

~/.ssh$ ls
id_ed25519  id_ed25519_anotheraccount  id_ed25519_anotheraccount.pub  id_ed25519.pub  known_hosts

Add the new private key (id_ed25519_anotheraccount) to the SSH agent:

~/.ssh$ ssh-add id_ed25519_anotheraccount

Add the new public key (id_ed25519_anotheraccount.pub) to your new GitHub account (Settings -> SSH and GPG keys -> New SSH Key).

Modify the SSH config:

~/.ssh$ touch config
~/.ssh$ subl -a config

~/.ssh/config

#bretttolbert account
Host github.com-bretttolbert
    HostName github.com
    IdentityFile ~/.ssh/id_ed25519
    IdentitiesOnly yes

#anotheraccount
Host github.com-anotheraccount
    HostName github.com
    IdentityFile ~/.ssh/id_ed25519_anotheraccount
    IdentitiesOnly yes

Now the trick is to use "github.com-anotheraccount" in place of "github.com" if you need to force it to use the new SSH key.

I.e.

$ git remote add origin git@github.com-anotheraccount:anotheraccount/anotherproject.git

Alternatively you can set the host in this git config:

[remote "origin"]
        url = git@github.com-anotheraccount:anotheraccount/anotherproject.git

And don't forget to set your name and email when you switch accounts:

$ git config user.name "anotheraccount"
$ git config user.email "anotheraccount@gmail.com"
 
Share this