[Google-oriented Programming(GoP)] Use multiple SSH keys within git commands

Github or Gitlab use ~/.ssh/id_rsa as the default SSH private key. But sometimes you need more accounts than one for access to Github or Gitlab and similar tools. For example you can have one account for your projects at home and second account for your company.

There are three ways to Use multiple SSH private keys within git commands.

Prerequisites

SSH Key

Check out our guide to generating SSH keys or troubleshoot common SSH Problems.

Configuration

Replace with your private key(such as ~/.ssh/id_rsa) while execute the next commands.

(Recommand)First option, Git configuration

It will configure sshCommand for per git repository.

1
2
# 
git config core.sshCommand "ssh -i <Your SSK private Key> -F /dev/null"

It will insert sshCommand to [core] segment within .git/config file.

1
2
[core]
sshCommand = ssh -i <Your SSK private Key>

Second option, Shell Environment Variable

1
2
# 
GIT_SSH_COMMAND="ssh -i <Your SSK private Key>"

Can append GIT_SSH_COMMAND environment variable to your shell bash. Such as ~/.zshrc, ~/.bashrc, etc.

Third option, SSH configuration

Assign different Hosts for multiple host reposities within ~/.ssh/config.

1
2
3
4
5
6
7
8
9
10
11
12
# vi ~/.ssh/config
Host <Your Git Account 1>_github
HostName github.com
# User git
PreferredAuthentications publickey
IdentityFile <Your SSH Private key 2

Host <Your Git Account 2>_github
HostName github.com
# User git
PreferredAuthentications publickey
IdentityFile <Your SSH Private key 2>

Must use <Your Git Account 1>_github or <Your Git Account 2>_github instead of git.com while use git command. Such as:

1
git clone git@<Your Git Account 1>_github:<Your repository>.git

SSH Agent

Remember to add SSH Key to SSH Agent to make your SSH private key available for git command.

1
2
3
4
5
6
7
8
9
10
11
12
13
# Delete all cached keys.
ssh-add -D

# Enable ssh-agent.
eval `ssh-agent -s`

# Check that your keys were added.
ssh-add -l

# If you haven't any entries then you should add your keys
ssh-add <Your SSH private key>
# ssh-add <Your SSH private key 1>
# ssh-add <Your SSH private key 2>

That’s all done! Now you can use different SSH private keys for multiple git reposities.

References

[1] My Profile | Cloudflare - Web Performance & Security https://coderwall.com/p/7smjkq/multiple-ssh-keys-for-different-accounts-on-github-or-gitlab

[2] How to Manage Multiple SSH Keys https://www.freecodecamp.org/news/how-to-manage-multiple-ssh-keys/