Books

Saturday, November 01, 2014

How to Use Multiple SSH Keys

This post is a quick How-To.

It shows how to create multiple SSH keys for accessing multiple remote servers from a single local machine.

The post would use git hosting services: Github and GitLab (which allows for SSH connection to hosted repos), to illustrate the steps. Say for example, at work you use Gitlab but for personal projects you use Github, and you want to be able to use SSH to interact with these two services from the same local machine.

Although Git hosting services are used here, the steps outlined is in no way tied to these git hosting services, it works just the same for any SSH connections.

First Step: Generating the SSH Keys.

The git hosting service would provide you the instruction for generating an SSH public/private key and how to add the public key to your account. For examples see Github's instruction.

It basically involves running this command:
ssh-keygen -t rsa -C "Comments you want attached to the key"



And then copying the public key generated (the .pub file) created by the command below to your account.

For a general introduction to the process of generating ssh keys that is agnostic to any git hosting service, see SSH keygen tutorial

Do this for all the multiple SSH identities you want.

Second Step: Configuring the Config Keys.

Let say following the above instructions, you generated two SSH keys. One for Github and Gitlab. Listing the contents of your ~/.ssh would then give:

github  github.pub gitlab gitlab.pub  config  id_rsa  id_rsa.pub  known_hosts

github, gitlab and the default id_rsa are the private keys while the files with the .pub extensions are the public keys.

The next thing to do now is to configure your SSH client to be able to use the appropriate key when accessing any of the remote servers it has its public keys.

This is done by editing the config file in the ~/.ssh directory. Given the above keys, the config file should be configured thus:

# Github
Host github.com
 HostName github.com
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/github
 
# For Gitlab
Host gitlab.org
 HostName gitlab.org
 PreferredAuthentications publickey
 IdentityFile ~/.ssh/gitlab


The configuration is basically telling your SSH client the location of the SSH key that should be use in authentication depending on the host details of the remote server being connected to.

With this done, you can thus clone repositories from both git hosting services. ie:

git clone git@github.com:username/awesome_personal_project.git and
git clone git@gitlab.com:username/awesome_work_project.git

Peradventure you were using SSH for work, while for your personal project you had HTTPS, but now with this new trick you just learnt you want to change the remote URL from HTTPS to SSH? Then you can use the git remote set-url  to achieve just that.

git remote set-url origin git@github.com:username/awesome_personal_project.git

No comments:

Post a Comment