How to prevent bloating ssh-agents?

· by Gürkan · Read in about 2 min · (219 Words)

Sometimes you need to run an ssh-agent if you're deploying something which requires ssh keys. Running is easy, you generally do something like:

eval `ssh-agent` && ssh-add (some key)

And if this is an automated process, you may realize your server has tons of ssh-agent processes after a while. You might want to kill the created agent, and you'll probably try doing with that SSH_AGENT_PID enviroment variable.

I don't know why, and I hate to inspect, this approach fails. Probably someone is just cancelling the job before your kill statement runs or your terminal loses env variables thanks to that cool wonky tool you need to run while deploy.

For mitigating some of the problems I see, I started to search the latest agent pid right after running it and putting this info to a file.

ls -rtd $(pgrep ssh-agent | sed 's#^#/proc/#' | tr '\n' ' ') | tail -1 | sed 's#/proc/##' > ~/.latest_agent_pid

Seems hacky and disgusting, right? Well, it works. You can use something like this when you want to kill this after your job is done:

kill -9 `cat ~/.latest_agent_pid`

And for a safety feature you can remove the file itself after kill statement + check if there is a file before creating a new agent and decide to use or kill this PID.