Map SSH Keys To Git Projects
By Sudheer S
Using Git with SSH is a common practice among software developers. The convenience of not having to remember passwords is a huge productivity boost in software development workflows.
In a previous blog post, I wrote about managing SSH keys.
Having many SSH keys can cause few issues:
ssh-agent
doesn’t work well with too many keys.- Can’t always map SSH keys to servers in SSH client configuration. Both personal and company projects Git can be hosted on the same server or third-party service such as Github.
- Some Git hosting services do not allow you to use the same SSH key in more than one user profile. You are forced to have a unique SSH keypair per user profile.
- The SSH server might refuse to allow too many authentication attempts.
Git allows you to set the environment variable GIT_SSH_COMMAND
. If you set this environment variable, Git uses the
specified command for push
and pull
operations.
Example command:
export GIT_SSH_COMMAND='ssh -i /home/myuser/.ssh/id_xxx -o IdentitiesOnly=yes'
If you set an environment variable like this and then use git pull
or git push
, Git will use the identity id_xxx
.
IdentitiesOnly=yes
instructs SSH client to use the explicitly defined identity id_xxx
.
Take this one step further and add the above export
command in a shell script. Invoke the script via source
command to load the SSH identity you want to use before git pull
or git push
.
File path: /home/myuser/bin/my-git-identity.sh
export GIT_SSH_COMMAND='ssh -i /home/myuser/.ssh/id_xxx -o IdentitiesOnly=yes'
The next time you have to use this specific SSH identity for git pull
, invoke it:
source /home/myuser/bin/my-git-identity.sh