uwtekg
Last Updated: March 21, 2017
·
22.32K
· celc
Ebc47ee771e1695743e6b79c0821f37f

An overview of dealing with Git and SSH keys.

I have an issue where I need to be able to deal with a non-trivial amount of git repos by different owners which results in hundreds or thousands of SSH keys.

The default

Put key as ~/.ssh/id_rsa which is tried by default on git clone git@github.com:Celc/jack-bower.git

Cons: Assumes only 2 keys ~/.ssh/id_rsa and ~/.ssh/id_dsa.

SSH Config

Add an ~/.ssh/config allowing you to specify aliases and their keys:

Host jackbower
  Hostname github.com
  IdentityFile ~/.ssh/id_rsa.jackbower

Which is tried on:

git@jackbower:Celc/jack-bower.git

Cons: There's some setup cost each time you want to do this and it couples the location you are cloning to, to an alias, so you'll need to constantly rewrite the locations to match.

Use a keychain

ssh-add ~/.ssh/foo
ssh-add ~/.ssh/bar
ssh-add ~/.ssh/baz

Which tries all keys on:

`git clone git@github.com:Celc/jack-bower.git`

Cons: There's a default limit to the number of keys you can try. The time to auth increases by the number of keys.

Use keychain and add/remote keys

ssh-add ~/.ssh/foo

Which is tried on:

`git clone git@github.com:Celc/jack-bower.git`

Then remove it:

ssh-add -d ~/.ssh/foo

Cons: There's still a lesser impact of the default cap and time increases with concurrency. It might be possible (but not investigated) that there's a race condition when the key is getting removed by one process and added by another.

Use a short lived keychain.

ssh-agent takes an optional command argument, so we could add keys that only exists for the duration of the subprocess.

ssh-agent bash -c 'ssh-add /Users/kitsunde/foo; git clone git@github.com:Celc/jack-bower.git'

Juggle environment variables with $GIT_SSH

There's a facility for specifying the SSH command to use in git which we can use by creating an application ~/git-ssh.sh:

#!/bin/sh
ssh -i "$GIT_SSH_KEY" "$@"

Make it executable chmod +x ~/git-ssh.sh and then:

export GIT_SSH=~/git-ssh.sh
export GIT_SSH_KEY=~/my_other_key

Which will be called as normal:

git clone git@github.com:Celc/jack-bower.git
Say Thanks
Respond
Filed Under