Tuesday, March 17, 2020

Using multiple ssh keys with Github (or any other host)

Imagine you're working on one machine with multiple clients. In that case each client might require you to have a separate account on Github. This means that you need to have separate SSH keys for those accounts too and that in turn means is a pain in the butt to have it working.

If you're on Linux (and probably MacOS too) there's hope for you! Follow those simple steps to get everything setup so that you won't even notice it is there!

Step 1: Add a host entry in ~/.ssh/config

Host client-github.com
     Hostname github.com
     User git
     IdentitiesOnly yes
     IdentityFile ~/.ssh/client_rsa

This allows you to connect to a host named client-github.com which will in fact connect to github.com but with a specific identity file (ssh key)

Step 2: Add the following 2 entries to your ~/.gitconfig

[url "ssh://git@client-github.com/client"]
        insteadOf = ssh://git@github.com/client

[url "ssh://git@client-github.com/client"]
        insteadOf = git@github.com:client

Using client-github.com is not really practical. There are instances (like linked npm modules from github.com) where you're not directly in control of the hostname. That's where the URL substitution in Git comes in handy. Whenever someone requests a URL from the client's namespace we substitute it with our custom address and everything's golden

Obviously if you substitute the client part of the custom hostname with the name of the client it will be easier for you to manage multiple such cases :) Just sayin'...

Have fun!

No comments: