In this article I will show you how you can use and manage different SSH keys for different Github accounts. Since Github does not allow you to use the same SSH key twice, we need to create one for each account. This is also true for other Git-based source code repository hosting services such as Gitlab and Bitbucket.
The use case
We have two different Github account that we want to access using SSH.
- Work
- Personal
Create SSH keys
First we need to create ssh keys for our accounts. We can do this by entering the command in our terminal twice.
ssh-keygen -t rsa
You will be prompted to enter a name. I would recommend giving it a name that describes its use e.g. work-github-ssh or personal-github-ssh.
Edit/Create SSH config file
Now we have to edit our ssh config file. If you don't have a ssh config file, create one under ~/.ssh/ named config. Add the following to your file.
# Personal github account
Host github.com
HostName github.com
IdentityFile ~/.ssh/personal-github-ssh
IdentitiesOnly yes
# Work github account
Host github.com-<you-work-github-username>
Hostname github.com
IdentityFile ~/.ssh/work-github-ssh
IdentitiesOnly yes
This is what tells our SSH configuration which SSH key to use.
- Host, tells us which host we want to connect to.
- Hostname, defines the domain we want to connect to.
- IdentityFile, tells us which key to use.
- IdentitesOnly, tells our configuration to only use keys provided by CLI and not by e.g. ssh-agent.
Edit Git configurations
Now, we need to make sure our Git configuration files are set to connect to the matching url for our work Github account in our SSH config. We'll leave our personal account as "default" so all Git configurations related to our personal account we'll just use "git@github.com:(repo path)", since this is what we defined in our config file as Host. For our work account, we do the following.
[remote "origin"]
url = git@github.com-<work-github-username>:<github-username>/<your-repository>.git
fetch = +refs/heads/*:refs/remotes/origin/*
Now, whenever we want to connect to our Git repository, our ~/.ssh/config file will automatically use the correct SSH key.
Add public SSH key to Github
Lastly, we have to add our public SSH key to our Github account.
Then, we navigate to SSH and GPG keys.
We then press the 'new SSH key' button in the upper-right corner and add our corresponding public key to our account.
Conclusion
In this article I have shown how we configure our ssh configuration so it allows for us to use Git with SSH on multiple accounts, without having to manually change which SSH key we want to use when deploying to Git.