Skip to content

Instantly share code, notes, and snippets.

@publicJorn
Last active June 17, 2022 16:41
Show Gist options
  • Save publicJorn/847ec2372dbddb98cdc4e949609c8b68 to your computer and use it in GitHub Desktop.
Save publicJorn/847ec2372dbddb98cdc4e949609c8b68 to your computer and use it in GitHub Desktop.
How to setup extra ssh keys when using different

Setup multiple SSH Keys for different github accounts

For osx

Create different public key

Create different ssh key according the article: Generate new SSH key

$ ssh-keygen -t ed25519 -C "my_email@provider.com"

for example, 2 keys created at:

~/.ssh/id_rsa
~/.ssh/id_other-account

then, add these two keys as following

$ ssh-add -K ~/.ssh/id_rsa
$ ssh-add -K ~/.ssh/id_other-account

-K saves it to the keychain

You can delete ALL cached keys with

$ ssh-add -D

You can check saved keys with

$ ssh-add -l

Modify the ssh config

$ vim ~/.ssh/config

Then add:

# Main account
Host github.com
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_rsa
  IdentitiesOnly yes

# Other account
Host github.com-other-account
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_other-account
  IdentitiesOnly yes

Host *
  AddKeysToAgent yes
  UseKeychain yes

The last bit is only needed if you supplied -K with ssh-add.
So you won't have to re-type your password after restart computer

Of course you can use a single key for other git providers as well, like gitlab or bitbucket.

Clone/update the repo

When cloning a repo, provide the host of the account you want to use

$ git clone git@github.com-other-account:<username>/<repo>.git targetdir

If you need to update an existing repo, you can update the targetdir/.git/config file by typing

$ git remote set-url origin git@<host-in-ssh-config>:<username>/<repo>

Or manually edit the config file

Set git username

This is not required for access, but used in commits.
You can set this globally for your main account and locally for your "other-account".

Set globally for your main account:

$ git config --global user.name "Jorn"
$ git config --global user.email "my_email@provider.com"

Set in project for the other account:

$ git config user.name "Jorn"
$ git config user.email "my_email@some-project.com" 

If there are multiple repo's connected to the other account this becomes tedious.
You can extend the global config by a directory match pattern:

~/.gitconfig

[user]
    name = Jorn
    email = my_email@provider.com

# note the trailing /
[includeIf "gitdir:~/workdir/"]
    path = ~/workdir/.gitconfig

~/workdir/.gitconfig

[user]
    email = my_email@some-project.com

This will enable the alternate email address for ~/workdir/ recursively.

Ready, set, go!

Credits:

@tomg-cloudnatix
Copy link

Note that [includeIf "gitdir:~/workdir/"] should end with a / to catch all sub dirs.

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