How to use a unique SSH key per git repo

If you're like me you're using git and have a number of repositories. Most of these are on an internal server. However a few are on github or a customer's server.

Now personally I don't like spreading my ssh key around especially to servers outside of the work environment. So I have a seperate ssh key for git hub and one for each customer's server.

Of course the problem then becomes, how do you tell git to use a specific key for a repo.

My first thought was to do this through .ssh/config and set an identity file for each host. This works just fine except for when I have su'ed to a different user. Then you either have change that user's .ssh/config or come up with another solution.

The other solutionm which is the one I'm using, is to use an ssh wrapper.

First wirte a litte script I called git_ssh_wrapper

ssh_key=$(git config ssh.key)

if [ -z "$key" ]; then
  ssh_opts="-i ${ssh_key}"

exec ssh $ssh_opts "$@"

We put it /usr/local/bin but anywhere that is in all user's paths is fine.

Next you have to tell git to use the wrapper instead of the normal ssh program. This requires the $GIT_SSH environmental variable to be set. We did it globally in /etc/profile but in each users .bash_profile it could also be done.

FInally you have to tell the git repo to use the correct key. Now when you do a git push or otherwise talk to the server via ssh it will use the key specific for that repo.

Last modified: Tue May 29 21:05:46 EDT 2012