Contributing with multiple Github accounts without hassle
2024-09-27 20:40If you are using Github, you probably have your git settings and ssh keys setup so that you don’t really ever have to think about authenticating to Github while pulling or pushing code. Setting this up for one Github account is simple, but what if you want to use a different account based on the repository you’re working in? With multiple ssh keys setup, contributing to different repos with different accounts is a breeze. So let’s get started on setting this up on macOS.
SSH keys
Start by creating separate ssh keys for each Github account you need to use. Maybe you already have one for your work account? Then go ahead and create one for your personal account. Add the keys to your account by following the instructions on Github.
Use the -f option for ssh-keygen to provide a name for the generated key:
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_user1 -C "email_for_user1@example.com"
ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_user2 -C "email_for_user2@example.com"~/.ssh/config
To associate the generated ssh keys with repositories, we can setup some ssh configuration in ~/.ssh/config. If this file does not exist yet, create it and then open it in your editor. Then add something like the following:
Host github.com
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/id_ed25519_user1
Host user2.github.com
HostName github.com
User UserNameForAccount2
AddKeysToAgent
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_ed25519_user2
IdentitiesOnly yesThis config differentiates the github.com host and the user2.github.com host, so that if nothing special is done, user1 is being used, and then with additional git configuration, user2 can be used automatically. Let's look at that git configuration next.
.git/config
Now we just need to set up some repository specific settings for repos where we want to use the user2 account with. Open the repository specific git configuration file at .git/config, located at the root of the repository directory (on your computer). Here, you need to modify the remote origin url and the user settings for the repo (note: there are lots of other settings in the file, do not touch those settings):
[remote "origin"]
url = git@user2.github.com:<repository_name>
[user]
name = UserNameForAccount2
email = useremail2@example.comThis tells that the remote host for this repo is user2.github.com, which our ssh config will know to use the ssh keys of user2 for and resolve the url to github.com. In fact, if you do not have the repository cloned yet, you can replace the @github.com with @user2.github.com while cloning, and the you won't need to change the remote "origin" url at all.
That's it
Now whenever you push from this repository, you will authenticate with the user2 ssh key, and your commits will show up with the information for the user2 account.