How to use different SSH keys for different services smoothly

While it’s obvious to use different passwords for different services, people using SSH keypair for logins think it is the secure way to do thing, thus use the same keys for all services. Even providers that requires to use SSH keys for authentication, only mentions to copy and paste your generated id_rsa.pub in the textarea, and go happy hacking.

When you ssh-keygen a new keypair, it asks you where to store them. At that point, be sure to choose an other name than the default choice. For instance, let’s save them at .ssh/id_rsa_launchpad, so your public key will be available at .ssh/id_rsa_launchpad.pub. When connecting to an SSH server, then you may pass it as an argument, so ssh will know which key file to use.

First, in the following example, we did not specify it explicitly.

# ssh -v -l nyuhuhuu bazaar.launchpad.net

debug1: Offering public key: /home/gabor/.ssh/id_rsa
debug1: Authentications that can continue: publickey
debug1: Offering public key: /home/gabor/.ssh/id_dsa
debug1: Authentications that can continue: publickey
debug1: No more authentication methods to try.
Permission denied (publickey).

SSH probes for the default keys, then it fails. Let’s add a command line argument that tells our identity file’s locatation.

# ssh -v -l nyuhuhuu bazaar.launchpad.net -i ~/.ssh/id_rsa_launchpad 

debug1: Offering public key: /home/gabor/.ssh/id_rsa_launchpad
debug1: Server accepts key: pkalg ssh-rsa blen 277
debug1: PEM_read_PrivateKey failed
debug1: read PEM private key done: type 
Enter passphrase for key '/home/gabor/.ssh/id_rsa_launchpad':

And now everything goes okay.

Things getting a bit more complex, when you need to reach a service that does not use the ssh command explicitly for connection. For example, when you want to push your code commits back to Launchpad, you can’t tell bzr about your identity file, and it simply tries the factory settings.

# bzr push  bzr+ssh://nyuhuhuu@bazaar.launchpad.net/~nyuhuhuu/+junk/django-html-mode

Permission denied (publickey).
bzr: ERROR: Connection closed: please check connectivity and permissions (and try -Dhpss if further diagnosis is required)

Pretty shame on it. The solution for this problem is to tell your ssh for which host which SSH keys to use. Open up ~/.ssh/config in your favourite text editor, and add the following to it:

Host bazaar.launchpad.net
  IdentityFile /home/gabor/.ssh/id_rsa_launchpad

A more convenient way is to also set your user name, and create an alias host for this settings, like this:

Host lp
  HostName bazaar.launchpad.net
  User nyuhuhuu
  IdentityFile /home/gabor/.ssh/id_rsa_launchpad

And now you really may go happy hacking.

# bzr push  bzr+ssh://lp/~nyuhuhuu/+junk/django-html-mode

Enter passphrase for key '/home/gabor/.ssh/id_rsa_launchpad':

It’s bad to see that this topic is not mentioned in the whole Launchpad Answers section—Github during the account setup process tells you all about.