Git: using different SSH keys in your repos
Git: using different SSH keys in your repos
When working with different projects and especially if you are a contractor that interacts with multiple clients, a common situation is that you have to access gitlab, bitbucket, github or other git cloud service with different credentials, usually to maintain access to other repositories while using an ssh-key that’s specific for a client.
Generating the key pair
If you haven’t generated a key yet, use the ssh-keygen command in git-bash. This generates public and private keys, by default in c:/Users/your_username/.ssh/. Make sure you specify a name for your new key that doesn’t overwrite any of the ones that are present in the .ssh folder. In this example our key is called id_rsa_second.
If you don’t know how to add the generated public to your bitbucket account, see how to Set up personal SSH keys on Windows in Bitbucket Cloud.
Cloning with a specific ssh private key
Be aware that if you are in Windows, these commands will not work in Power Shell or cmd. You need to use mingw that most client integrate.
To clone with a specific key we just need to set the GIT_SSH_COMMAND variable while we give the command. Easier done than said:
GIT_SSH_COMMAND="ssh -i /c/Users/your_username/.ssh/id_rsa_second" git clone git@bitbucket.org:your_repo/your_repo.git
Note that the path to the .ssh/id_rsa_second is Windows specific. In Linux it would be ~/.ssh/id_rsa_second
Associate one ssh key to one repository
Once the repo is cloned, cd to the repository and give the following command:
git config --local core.sshCommand "ssh -i /c/Users/your_username/.ssh/id_rsa_second"
This will add a line in the local git configuration file that tells git to use a custom key whenever ssh is invoked by git in that repo. Note that when omitting --local, it is implied.
You can check that it worked by opening the the git configuration with the command git config -e (or git config --local -e) which opens the default console text editor (the default editor can be changed with git config --global core.editor "nvim" or other editor of choice)
The config file should now look more or less like the following:
[core]
repositoryformatversion = 0
filemode = false
bare = false
logallrefupdates = true
symlinks = false
ignorecase = true
sshCommand = ssh -i /c/Users/your_username/.ssh/id_rsa_second
[remote "origin"]
url = git@bitbucket.org:your_account/your_repo.git
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master
The above solution was tested to be working in git-bash and with git-fork (ui client) and with mingw under windows. It works with all git cloud service providers.
Troubles?
- Check the path syntax. Does your OS or git client use a different syntax than “/c/Users/blah/blah/” for paths?