Using rsync from cron with ssh keys that have a passphrase

It took me some time to figure this one out, as everybody is using rsync and ssh-keys without passphrases, but I insist that an ssh-key should have a passphrase.

In my first attemts I got this error messages mailed to me by crontab:

Permission denied (gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive).

Here are the steps to automate a backup initiated from crontab using rsync, SSH and ssh-keys with a passphrase:

  1. Make a set of SSH keys.
  2. Setup SSH to use the agent automatically.
  3. Login once as the user who's cron will run the backup script. You will be asked for a passphrase. When the machine reboots, you will need to login once more, to enter the passphrase again.
  4. Make a backup script that includes some SSH variables.
    This script could be as simple as this:
    . /home/username/.ssh/variables
    rsync -avz --delete /data/ example.com:data

    N.B. This variables file only contains these lines:
    SSH_AUTH_SOCK=/tmp/ssh-DmFcb18036/agent.18036; export SSH_AUTH_SOCK;
    SSH_AGENT_PID=18037; export SSH_AGENT_PID;
    echo Agent pid 18037;
  5. Put that script in crontab.

That should do it for you, as it works like a charm for me!