How to connect to GitHub using different SSH identity files?

The identity files are part of the SSH protocol, which enables secure system administration and file transfer through Internet communications or insecure networks.

SSH uses public key authentication, which relies on cryptographic keys to authenticate the server. These keys are stored in the user's .ssh directory and are like advanced passwords that cannot (or should not) be stolen over the network. However, in practice, many keys are used for automation and do not require a passphrase.

Suppose you are at the point where you work for various clients or projects and need to configure multiple GitHub accounts to access their source code. In that case, it is very likely that you already need different SSH identities to access them without compromising security.

One way to achieve this is by updating your SSH configuration file to associate the identity file with the account you want to use.

To do this, follow these steps:

  1. Open the SSH service configuration file with your preferred editor. I will use VIM for the following example.
    vim ~/.ssh/config
  2. Add the alias you want to use with the account associated with its identity file. You can do this as follows:
Host github.com-[alias]
    HostName github.com
    User git
    IdentityFile ~/.ssh/alias-id_rsa
~/.ssh/config (SSH Configuration file)

[alias] can be replaced with the name you want to use to associate the account, for example, the client's name. github.com-seisigma.

Save your changes and close the editor.

How do we use this configuration?

To illustrate the use of this configuration, let's say our alias is named google, which gives us the Host github.com-google. Our identity file would be named google-id_rsa. It would provide us with the following configuration file:

Host github.com-google
    HostName github.com
    User git
    IdentityFile ~/.ssh/google-id_rsa
~/.ssh/config (SSH Configuration file)

For a visual context, this is the standard way to clone a repository without using an alias:

git clone git@github.com:user/repo.git

And this is how we would call the same repository if we needed to use an identity file named google-id_rsa to complete the connection:

git clone git@github.com-google:user/repo.git

There you go! With this small change, we can access our repository securely.

Bonus

Why should we use different identity files for each SSH account?

It all comes down to security. First, If our private key falls into the wrong hands, it will jeopardize access to all resources that share the associated public key.

Second, another critical point is simplifying unlinking a key and the associated resource. It will only be possible if the key is associated with a single resource.

Consulted sources: