Use multiple SSH keys for different GitHub accounts
Rather than entering the username and password, you often use SSH keys to access GitHub repositories. It's a more secured and recommended way to communicate with remote GitHub servers.
Sometimes you have more than one GitHub account. For example, one for accessing personal repositories, another one for your daily works.
The question is how your local Git recogranizes a repository that comes with which GitHub account. This tip will help you.
Creating different keys
Assume that
`foo`
and
`bar`
are two GitHub usernames that you would like to use in the same computer. You can follow the official GitHub guide to
generate SSH key.
// Generate SSH key for `foo`
$ ssh-keygen -t ed25519 -C "foo@domain.com"
When you're asked to indicate the file to save the key, don't use the default key. Change the name of file to something associate with the account, for example:
Enter a file in which to save the key (/home/you/.ssh/id_ed25519):
`/home/you/.ssh/id_foo`
Repeat the same steps for the `bar`
account. Now, we have two private keys, `id_foo`
and `id_bar`
located at the `~/.ssh`
folder.
Adding keys to SSH agent
// Delete cached keys
$ ssh-add -D
// Start the ssh-agent in the background
$ eval "$(ssh-agent -s)"
// Add your SSH private keys to the ssh-agent
$ ssh-add ~/.ssh/id_foo
$ ssh-add ~/.ssh/id_bar
Mapping keys to GitHub repos
This step lets SSH know which private key should be used for particular hosts.
$ cd ~/.ssh
$ touch config
Add the following content to the `config`
file:
Host github.com-foo
HostName github.com
User git
IdentityFile ~/.ssh/id_foo
IdentitiesOnly yes
Host github.com-bar
HostName github.com
User git
IdentityFile ~/.ssh/id_bar
IdentitiesOnly yes
You'll realize that `github.com-foo`
and `github.com-bar`
look invalid hosts, but actually they are treated as aliases. SSH maps it with the `HostName`
option and uses the private key in the `IdentityFile`
option.
Changing GitHub settings
Let's say that the `foo`
account accesses a GitHub repose whose URL is `github.com/foo/a-foo-repos`
. Go to its cloned folder, and change the `.git/config`
file as below.
It's worth noting that the SSH host `github.com-foo`
created in the previous step is used:
[remote "origin"]
url = git@github.com-foo:foo/a-foo-repos.git
Apply the similar settings for the `bar`
repositories.