Sync remote git repos

Today I succesfully set up my first crontab, which runs a script that keeps two remote git repos in sync. This if course requires a server, where you can actually run cron, and local filesystem access, for a third ‘transfer’-repo. For added security, I use a custom ssh key during transfer.

  • First, generate a new ssh key, sans passphrase, on the server where you’ll run your cronjob. Leave the private key in ~/.ssh, install or copy the public one to both your remotes.
  • Add to ~/.ssh/config your two remote hosts, with the correct hostname, user, and specify your brand new private key as IdentityFile ~/.ssh/newprivatekey, and optionally set IdentitiesOnly yes.
  • Clone your repo from one of the remotes, and make sure git is configured with both remotes. Important: use the Hosts as defined in .ssh/config as the remote URL, so that git uses your special key. Otherwise git will go with the default key, which you probably don’t have installed on your server.
  • The script is simple, pull from both and then push to both remotes. Test it, and be aware it will fail on merge conflicts! In my case this is very unlikely, so I’m not handling that.
  • Run crontab -l to list your crontabs and use crontab -e to add one. I want to run my script every 5 minutes, so I added this line: */5 * * * * ~/cron/ >/dev/null 2>&1. See your favorite search engine for the meaning of the first 5 arguments. I end the string with piping stdout and stderr to /dev/null, otherwise I’ll get email notifications about the cronjob (you could use that to inform yourself of merge conflicts for example).
  • Done.