Managing multiple GitLab accounts or using different SSH keys for different projects can be tricky, especially when you need Git and SSH to automatically use the correct identity. Here’s a clean and reliable way to configure it.
Problem
When working with multiple GitLab repositories tied to different accounts or SSH keys, Git may use the wrong identity, leading to errors like:
ERROR: The project you were looking for could not be found or you don't have permission to view it.
Solution Overview
We solve this using:
- SSH Config Aliases – to map keys to specific hostnames.
- Git URL Rewriting – to route Git URLs through the right SSH alias automatically.
Step 1: Define SSH Config
Edit or create ~/.ssh/config
:
Host gitlab.com-user1
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_ed25519_user1
IdentitiesOnly yes
Host gitlab.com-user2
HostName gitlab.com
User git
IdentityFile ~/.ssh/id_ed25519_user2
IdentitiesOnly yes
Each Host
entry points to a unique key for a specific GitLab account.
Step 2: Configure Git URL Rewriting
Set Git to rewrite the standard GitLab URLs to your aliases.
git config --global url."git@gitlab.com-user1:user1/".insteadOf "git@gitlab.com:user1/"
git config --global url."git@gitlab.com-user2:user2/".insteadOf "git@gitlab.com:user2/"
This way, even if you clone using the standard URL, Git will internally reroute it.
If you’ve added a less-specific rule before (e.g., missing the namespace), remove it:
git config --global --unset url."git@gitlab.com-user1:".insteadOf
git config --global --unset url."git@gitlab.com-user2:".insteadOf
Step 3: Use Standard GitLab URLs
You can now clone or use remotes like:
git@gitlab.com:user1/repo-name.git
git@gitlab.com:user2/another-repo.git
Git will rewrite them automatically based on your rules, and SSH will use the correct key.
Step 4: Verify It Works
To confirm Git is using the correct SSH key:
GIT_SSH_COMMAND="ssh -v" git ls-remote origin
Look for a line like:
Offering public key: /home/youruser/.ssh/id_ed25519_user1
This confirms the correct key is being used.
Conclusion
With SSH config aliases and Git URL rewriting, you can work with multiple GitLab accounts or SSH keys seamlessly, without changing URLs manually or running into permission errors.
This setup is flexible, clean, and scales well across teams or machines.