Juggling Multiple SSH Keys

You probably have some ssh key files (~/.ssh/id_rsa{.pub,} or similar) kicking around if you've ever needed to use a service that uses public key cryptography, like Github or Heroku.

These id_rsa and id_rsa.pub files are private and public key files that you should keep quite secure.

But they don't have to be the only ones you ever use! In fact, it's probably best to have a separate pair of keys for each major service you use. At the very least, your personal keys and work-related keys should be different!

It's easy to create more keys. Here's a good wiki page.

  1. See existing keys with ls -al ~/.ssh

  2. ssh-keygen -t rsa -C "your@email.com"

  3. Answer the prompts. You can name it however you want.

Common failure mode: moving to a new computer

Well, you can move keys between computers and keep backups easily. Let's say you're moving to a new computer and don't want to remove all existing keys from every service and replace them with new ones. No worries, just do this:

  1. eval `ssh-agent -s` This makes sure ssh-agent is running.

  2. ssh-add -l will list out your existing identities that your computer knows about.

  3. ssh-add -K /path/to/private_key will add that to the list of identities that your computer knows about.

Common failure mode 2: ssh'ing with the right identity

Oh, you just ssh hyde@foo.com -I /path/to/identity, and if it's a pain, add that to your ~/.ssh/config:

Host foo.com  
  Port 22
  IdentityFile ~/.ssh/my_precious
  User hyde

Common failure mode 3: git getting all screwed up

Let's say you use different identities for Github and Bitbucket, and either is refusing a push because your identity is not the one it has on file.

Nothing to it! You can control ~/.gitconfig as well as repository_name/.git/config, and you already know you can configure ssh to do whatever your heart desires.

Let's say you have 2 Heroku accounts. Just make up stuff in your ssh config like this:

Host heroku.personal  
  HostName heroku.com
  IdentityFile ~/.ssh/uber_personal_key_right_here
  IdentitiesOnly yes

and then edit any desired repository's git config:

[remote "heroku"]
    url = git@heroku.personal:project_name.git

Basically, ssh configuration allows you to specify which identity should be used with which host.

Lots more about ssh configuration here.