Multiple SSH keys for Github and Gitlab ๐๐
July 11, 2019
2 minutesGit is one of the most used version control management software used by software engineers all over the world. Github has been well known as a leading remote repository hosting service for more than a decade.However collaboration limitations on private repositiries have attracted teams to use Gitlab.So why not use both and harness the best features provided by each repository hosting service.
Generate ssh keys
with different names.
$ ssh-keygen -t rsa -C "[email protected]"
When you see the following message, enter a unique name. I will be using id_rsa_home
for github and id_rsa_work
for gitlab.
Generating public/private rsa key pair.
Enter file in which to save the key (/home/username/.ssh/id_rsa): /home/username/.ssh.id_rsa_home
Next, you’ll be asked to enter a passphrase. Enter a secure one.So, you’ll have created SSH key for your home account(i.e Github).
Generate SSH keys for gitlab.
$ ssh-keygen -t rsa -C "[email protected]"
Enter name for file.
Generating public/private rsa key pair.
Enter file in which to save the key (/home/username/.ssh/id_rsa): /home/username/.ssh.id_rsa_work
Enter the paraphrase(a secure one again) and the key generation part is done.Now check all the keys created. You should see similar results.
$ ls ~/.ssh
id_rsa_home id_rsa_home.pub id_rsa_work id_rsa_work.pub known_hosts
Now you need a config file for organise these keys.
$ cd ~/.ssh
$ touch config
$ vim config
Add into the config file.
# GITLAB
Host gitlab.com
HostName gitlab.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_work
# You can also use gitlab.company_url.com as a Host and HostName instead
# GITHUB
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa_home
Next you’ll delete cached keys
$ ssh-add -D
#If the following message appears:
Could not open a connection to your authentication agent. Enter command below:
$ eval `ssh-agent -s` && ssh-add -D
Now add your keys
$ ssh-add ~/.ssh/id_rsa_work
$ ssh-add ~/.ssh/id_rsa_home
Now you can check connection
$ ssh -T [email protected]
#enter paraphrase for github
Hi github_user! You've successfully authenticated, but GitHub does not provide shell access.
$ ssh -T [email protected]
#enter paraphrase for gitlab
Welcome to GitLab, gitlab_user!
You may need to set git config user details for any project. It’s required to distinguish your accounts.
$ cd github_project
$ git config user.name "home_user"
$ git config user.email "[email protected]"