Handling multiple Git credentials the easy way

In this post I'm gonna quickly go over a nice and clean setup I use to manage authenticating with different accounts on a variety of different project repositories hosted on cloud services such as GitHub, GitLab, BitBucket, etc..

PREPARATION

As a first step, we want to make sure that all of our accounts use SSH keys to authenticate connections between our machines and the cloud providers. Nowadays the process doesn't require much fiddling, and can be simply done using our providers' web UIs. I won't go over this part because the specific way to set this up would be vendor-specific, and I don't consider this step to be complicated enough to require any explanation. \ Let's suppose that at this point we own two different GitLab accounts, each bound to a dedicated SSH key stored on our machine:

user: first
email: [email protected]
private key: ~/.ssh/first/id_rsa
public key: ~/.ssh/first/id_rsa.pub
repository name: first-project

user: second
email: [email protected]
private key: ~/.ssh/second/id_rsa
public key: ~/.ssh/second/id_rsa.pub
repository name: second-project

Configuring SSH

If not present, a SSH configuration file needs to be created:

cd ~/.ssh/
touch config

We are going to use said file to tell our machine to use different credentials depending on the host we're trying to connect it to.

This could lead us to a question:

We just assumed both our accounts are gitlab.com accounts. How do we use different credentials if the host is the same?

The answer is straightforward: ssh can be configured by using host alias names, which will basically allow us to treat the same underlying hostname as two different hosts, while still resolving the correct hostname. Let's see how to take advantage of this feature

# Gitlab.com - "first" account
Host gitlab.com_first   # <-- this could be any alias     
HostName gitlab.com     
User git    
Preferredauthentications publickey    
IdentitiesOnly yes    
IdentityFile ~/.ssh/first/id_rsa

# Gitlab.com - "second" account
Host gitlab.com_second  # <-- this could be any alias     
HostName gitlab.com    
User git    
Preferredauthentications publickey    
IdentitiesOnly yes    IdentityFile ~/.ssh/second/id_rsa

Configuring Git

Our job is pretty simple now: we need to let git use our alias hostnames in order to provide the correct SSH credentials when trying to authenticate (using only our "first" account for brevity):

# If the remote repo is still not cloned locally
# we just need to provide our alias hostname
# when cloning
git clone [email protected]_first:first/first-project.git

# If the remote repo is already cloned locally
# we need to update the remote's hostname. Here# we're assuming "origin" its name.git remote remove origin
git remote add origin 
[email protected]_first:first/first-project.git

DONE

We're done with our configuration, now the correct credentials will be used when connecting to each remote.


Publication date: 25/07/2020