I am trying to set up multiple ssh keys for two different github accounts but I can't seem to get it to work like I'd like.
Currently I have two ssh keys, we'll call them a_rsa
for repos cloned from github.com-a and b_rsa
for repos cloned from github.com-b.
I'm on Ubuntu and all my keys and config are located in ~/.ssh
. My ssh config looks like this:
#Account A
Host github.com-a
HostName github.com
User git
IdentityFile ~/.ssh/a_rsa
#Account b
Host github.com-b
HostName github.com
User git
IdentityFile ~/.ssh/b_rsa
and an example url in one of my .git/config
files is:
url = git@github.com:a/SomeRepo.git
No matter which repo I am in when I try to push or pull from master it always tries to use key b_rsa.
I have tried changing the User on each to a
and b
respectively to no avail. I'm not sure if my config is even being read as I have tried setting my config file to just this:
Host *
IdentityFile ~/.ssh/a_rsa
And all my repos still try to use the b_rsa
key.
The way I would like it to work is based on the owner of the repo I am tyring to push to (owner a
or b
) it would use the appropriate key but I can't seem to figure out what is wrong.
The problem is in the URL for the repositories.
You should be using the Host
in the git repository URL and not the Hostname
from the ~/.ssh/config
Therefore, the URL in your repositories .git/config
should be either
url = git@github.com-a:a/SomeRepoForUserA.git
OR,
url = git@github.com-b:b/SomeRepoForUserB.git
Using the correct Github identity while making commits
The other thing you would want to do, if the username and email address for these repositories are different, then while making commits to these repositories, you should use the corresponding username, email like so:
git -c user.name="UserA" -c user.email=UserA@blah.com commit -m "Commit done to repository A"
AND,
git -c user.name="UserB" -c user.email=UserB@blah.com commit -m "Commit done to repository B"
Fixing commits with incorrect username, email
If you have already made commits with the incorrect author and user, this should be used to fix it.
git -c user.name="UserA" -c user.email=UserA@blah.com commit --amend --reset-author
Ofcourse, the above fixes only the most recent commit. If there are older commits you could an interactive rebase (git rebase -i
) combined with the above command OR, use filter-branch
Try with
IdentitiesOnly yes
IdentitiesOnly
Specifies that ssh(1) should only use the authentication identity files configured in the ssh_config files, even if ssh-agent(1) offers more identities. The argument to this keyword must be ''yes'' or ''no''. This option is intended for situations where ssh-agent offers many different identities. The default is ''no''.