Git Configuration - Using Corresponding SSH Keys for Multiple Git Services
In actual development, encountered this problem: company service uses GitLab, personal side projects use GitHub, both have different accounts. For example, my company email is he@company.com, GitHub is personal email he@1991421.cn. I don’t want to use the same Key, hoping to use corresponding authentication Keys for different Git services. After searching online, the method is as follows.
Configuration Steps
- Generate SSH-key
cd ~/.ssh/
# Generate for GitHub usage, use default name by pressing enter
$ ssh-keygen -t rsa -C "he@1991421.cn"
# Generate for company GitLab usage, rename to id_rsa_company
$ ssh-keygen -t rsa -C "he@1991421.cn"
This way both keys are generated separately, no conflict
Paste public key to corresponding platform
cat id_rsa.pub
cat id_rsa_company.pub
Configure config Execute
touch config
, create configuration file Paste the following configuration into it
# company-GitLab
Host compay.com
IdentityFile ~/.ssh/id_rsa_company
# GitHub
Host *
IdentityFile ~/.ssh/id_rsa
\* means match all others
- Test if successful
# GitHub
ssh -T git@GitHub.com
# Internal network GitLab
ssh -T git@192.168.1.150
No error means OK. This way you can normally pull repositories and submit code.
Username/Email
Token differentiation only solves authentication permissions, but the commit username and email will still be default global configuration. If you want to personalize, need to execute the following commands in the repository.
$ git config [--global] user.name "[name]"
$ git config [--global] user.email "[email address]"
If you want to automatically use one set of configuration for company repositories and another set for personal projects, so you don’t have to manually set it every time you pull a repository. For specific operations, you can click here
Common Issues
- SSH login, prompts permission denied
Ensure password, configuration are correct. If still prompting, the possibility is actually in permissions. Make sure
.ssh
folder permissions, recommend directly 777