How to get SSH Keys Loaded in Your Cron Job's Environment

I have a cron job that runs every 6 hours. It basically generates a podcast RSS feed for bassdrive.com (great online station I’ve been listening to for years). Originally I was hosting this RSS feed on my own server, which was no big deal, even with the 20,000 hits per day it gets. RSS clients are hungry for new episodes so it seems. But figured, if Github can host it for me, why not?

So I came up with the crontab line:

0 */6 * * * /bin/bash /home/username/bassdrive/run.sh 2>&1

Which would output the RSS file to a public directory then git commit and push to the git repo of https://github.com/voidet/bassdrive-podcast. It made the file, but couldn’t push to github, because it didn’t have ssh keys loaded into the environment.

How to Load SSH Keys

I found this howto which ran me through how to use keychain. Ultimately, these were the steps needed:

sudo apt-get install keychain
/usr/bin/keychain "$HOME/.ssh/id_rsa"
0 */6 * * * . "$HOME"/.keychain/${HOSTNAME}-sh; /bin/bash /home/username/bassdrive/run.sh 2>&1

Notice how all I had to do was load the keychain via that prepended command to the existing crontab command. Keychain just appears to be some beautified access tools to the already existing ssh tools. But super simple! Now I have my script just committing changes back up to the git repo!