How to use your github ssh keys for different accounts

eraywebdev

Eray Kaya

Posted on March 12, 2023

How to use your github ssh keys for different accounts

When you have couple different github accounts and different permissions for each of them it can get tricky to manage your projects. I found the best way is to use ssh and create a ssh config file to manage which key is for which github account.

Create a ssh key from your terminal:

ssh-keygen -t rsa -b 4096 -C "foo@bar.com"

Copy and paste the outcome to :
github -> settings -> SSH and GPG keys -> New SSH key

Now you should have .ssh folder, in there manage your keys like for example if you have 2 different keys you should have 4 folders like: work-ssh, work-ssh.pub, personal-ssh, personal-ssh.pub

Create a file called config without any extension to name and add this config:

Host *
IgnoreUnknown UseKeychain

// Personal GitHub account

Host github.com
HostName github.com
User git
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/personal-ssh

// Work GitHub account

Host github.com-work
HostName github.com
User git
AddKeysToAgent yes
UseKeychain yes
IdentityFile ~/.ssh/work-ssh
Enter fullscreen mode Exit fullscreen mode

To use work ssh above you need to clone the repo like this:

git@github.com-work:[Project Group]/[Project Name].git

To use personal ssh above you need to clone the repo like a regular repo:

git@github.com:[Project Group]/[Project Name].git

Also keep in your mind that author will be the current global user if you don't change your global git user you can commit with wrong account even though you don't have access on github. So, to make it simple here is how I created my alias to change global git config in powershell:

Function GitCurrentUser { 
git config user.name; 
git config user.email 
}
Set-Alias -Name gcur -Value GitCurrentUser

Function SwitchToPersonal { 
git config --global user.name "[Your Gh user name"; 
git config --global user.email "[Your Gh Email]"; 
git config user.name; 
git config user.email 
}
Set-Alias -Name gpersonal -Value SwitchToPersonal
Enter fullscreen mode Exit fullscreen mode

Feel free to comment if you have questions!

💖 💪 🙅 🚩
eraywebdev
Eray Kaya

Posted on March 12, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related