How to Configure Multiple SSH Keys with multiple Github Account
Often you might have used Github SSH key for avoiding to enter username and password again and again. I too prefer the approach as it is less annoying and works like a magic. We will use terms personal for referring to our personal Github account and work to our organization account.
Prerequisites
- Generating SSH Keys
- Add SSH Key to your Github Account (separate for both account personal/work)
- Creating SSH Agent Config to specify ssh keys for different host
Generating SSH Key
- Open the terminal and execute below commands
ssh-keygen -t rsa -b 4096 -C "yourpersonalemail@gmail.com"
- It will ask you for the filenames keep it default
- Again execute the same command with changed parameter
ssh-keygen -t rsa -b 4096 -C "workemail@org.com"
// choose filename different eg id_rsa_work.pub for public key
// similarly for private key filename id_rsa_work
Add SSH Key to Github Account
Add the generated public keys to your personal/work Github Account in your account settings page. Refer https://docs.github.com/en/articles/adding-a-new-ssh-key-to-your-github-account.
Creating SSH Agent Config
As the ssh url will be different for both your personal/work account we need to make some tweaks inorder to apply proper SSH Key to each account.
#Default github# Save file at ~/.ssh/configAddKeysToAgent yesHost github.com
Hostname github.com
User git
IdentityFile ~/.ssh/id_rsa
Host organization.github.com
Hostname github.com
User git
IdentityFile ~/.ssh/id_rsa_work
So we have configured most of the settings but there is one more puzzle we need to solve. If you have configured github global.config.username it will be used as username for commit messages in your work repo too. We need to make some changes to our global git config file.
// filelocation: ~/.gitconfig
[user]
name = kailashyogeshwar85
email= kailashyogeshwar85@gmail.com
[includeIf "gitdir:~/project/work/"]
path = ~/project/work/.gitconfig
As we can see we are referring different gitconfig file for our work repositories. Lets see the contents
// filelocation: ~/project/work/.gitconfig
[user]
name = organization_username
email= workemail@work.com
Cloning repository
Default url for org repository is:
git@github.com:org/repoName
change url to
git clone git@work.github.com:work/repoName
TADA! You have successfully configured two Git Accounts with two separate SSH Keys no more worries to enter password.