Sunday, December 25, 2016

Multiple Github accounts and repository setup over SSH

Hello Friends,

Am posting something which is not new as a problem and pretty sure if any of you are/were facing this issue then you must have got your solution. But summing up here so that it could get simple and short.

Well but what's the problem?
Problem: is, for people dealing with code (or dealing with anything where they put their assets (like code files, xmls, ymls etc)) on Github repositories(but in more than one account) and they don't know how to setup different ssh keys for different account (in Github) and setup git config's user.email and user.name different for different repositories

First step:
Create different ssh keys (for each of different Github account)
but at "Step 3" don't use the default path instead provide custom name,
e.g /Users/you/.ssh/id_rsa_github_username_one

 
Image courtesy: https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/

and add keys to ssh-agent

Image courtesy: https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/

Second step:
Now the interesting (may be new for some) part.
Setup ssh configs (to use different ssh keys for different account)
1. Open a Terminal window
2. Create a file (if not already there with touch)
touch ~/.ssh/config
3. Append content to ~/.ssh/config
#Username one (username.one@email.account) account
Host github.com-githubusernameone
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_github_username_one
 

#Username two (username.two@email.account) account
Host github.com-githubusernametwo
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa_github_username_two


Third step:
Append keys in respective github account.
Visit: Github (login with valid credentials)
Visit: https://github.com/settings/keys or traverse Settings > SSH and GPG Keys

Fourth step:
As such things are 99% setup and but there are few small but important steps pending.
instead of original git repository url like
git@github.com:github_username_one/some_repository_one.git
Use
git@github.com-github_username_one:github_username_one/some_repository_one.git
For git cloning and repository setup
and also don't forget to setup git config's user.email and user.name (without the use of --global flag) like
git config user.email "username.one@email.account"
git config user.name "Github username one"
Do the same setup (with localized values) for other repositories and we are good to go.