Multiple SSH Keys on Git Accounts
Hi,
In this post we'll explore how to use different SSH
keys and pair them with an specific git account.
The first thing that we'll do is create two different SSH keys:
$ ssh-keygen -t rsa -C 'your_email@youremail.com'
We'll execute that command the number of times that we want a new/different key, then it should show something like this:
~/.ssh/id_rsa_oscarmcm_work
~/.ssh/id_rsa_oscarmcm
Now we need to add these two keys to the SSH
agent by doing this:
$ ssh-add ~/.ssh/id_rsa_oscarmcm_work
$ ssh-add ~/.ssh/id_rsa_oscarmcm
Now we need to modify the SSH config in order to tell the agent which key it will use for the host:
$ cd ~/.ssh/
$ touch config
$ vim config
And now add the following lines:
# Work account
Host github.com-work
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_oscarmcm_work
# personal account
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_rsa_oscarmcm
And now when we clone the the repository we need to change the clone URL a bit, so use the following example:
git clone git@github.com-<sshID>:myGitHubAccount/myRepo.git
So that will be translated to:
git clone git@github.com-work:gorillaz/melancholly-hill.git
And just in case GIT doesn't update the remote URL, you need to change it too:
$ vim .git/config
[remote "origin"]
url = git@github.com-work:gorillaz/melancholly-hill.git
And now, you can use a different SSH key for your commits:
Bonus
GIT also offers a feature to conditionally includes a custom config based on an specific path, so if you use a different directory for all your work repos (let's say ~/work/), then you can specify the following in your ~/.gitconfig to automatically use your work credentials inside them:
[includeIf "gitdir:~/work/"]
path = ~/git-work.conf
Each conf file can then define it's own user, e.g. ~/git-work.conf:
[user]
name = Oscar Cortez
email = work@hoscarmcm.com
There, all set now! Whenever you are working inside a repo that lives under ~/work
, Git will automatically use your work email.
And that's it, I hope you liked this post.