Giorgio's Blog

Using keychain to manage ssh agents

Recently it dawned on me that there's some seemingly obvious tools of the trade that may be helpful to write about. In that spirit, here's a quick post about one such tool, Keychain.

Back in 2015, I worked as an application developer for the infrastructure department of a leading backup and disaster recovery company. One of the responsibilities of that team was ensuring our massive fleet of storage servers were online and healthy. What this meant was occasionally the team would have to remotely connect to them (via SSH) through a "jump box" or Bastion host.

As you can imagine, this quickly gets tedious if you need to connect to a few servers throughout your day. Inevitably, people would start adding things like eval ssh-agent to their bash or zsh rc files. What they generally neglected to do however, was clean up those ssh agents when they were done with them. This lead to many agents running for a given user, and while they may not be large processes, it is a waste of resources on a shared host.

Enter keychain. Keychain is a wrapper around the ssh-add and ssh-agent commands that makes it simple to manage your keys and clean them up correctly. All you need to do is add eval keychain --eval to your shell configuration and presto, no more duplicated ssh-agents! It's such a nifty tool that I even use it locally. For instance, the same messy ssh-agent command above could "leak" across multiple tabs in your terminal emulator. Keychain eliminates that.