Backing Up Daily, Weekly, and Monthly with Cron

Now that my Mastodon server is making regular backups, I want to preserve some of the backups on the off chance something goes desparately wrong with my configuration and I have to do a very large rollback.

It turns out, while cron is maybe not the friendliest tool around, it makes this task very easy. What I want to do is a three-tier backup: daily, weekly, monthly. I only plan to keep one instance of each.

So in my archives user, I’ve created three directories: daily, weekly, and monthly. Now, I install cron rules for two users. To install these rules, I login as the user and do crontab -u ${USER} -e.

The first rule is installed in the mastodon user and creates a daily backup.

37 1 * * * cd /home/mastodon/live/admin && ./make-archive /home/mastodon/archive > /home/mastodon/archi
ve.log 2>&1

I leave this plenty of time to run because archiving the live/public/system subdirectory takes forever.

I make sure the archives user is in the mastodon group so it can access the archives that are being created. Then for my archives user, the rules I need are simple: grab the archive daily, then keep references to it weekly and monthly.

15 4 * * * cp /home/mastodon/archive/archive.tar.gz /home/archives/daily/mastodon_archive.tar.gz
15 9 * * 1 mv /home/archives/daily/mastodon_archive.tar.gz /home/archives/weekly/mastodon_archive.tar.gz
13 9 1 * * mv /home/archives/daily/mastodon_archive.tar.gz /home/archives/monthly/mastodon_archive.tar.gz

This is a simple family of rules, but it does the job. Remembering that the fields in cron are minute, hour, day-of-month, month, day-of-week, these rules do:

  • a daily copy of the archive into the archival space
  • a weekly move from the current daily backup to a weekly backup
  • a monthly move from the current daily backup to a monthly backup

The system is a little fragile (there’s a risk that a damaged daily archive, unnoticed for a month, kills all our archives). But with a minimum of maintenance it should take care of itself.