Creating backups from Linux to Google Drive

Google Drive is a great platform, where you can store your files. It has a limited capacity with the free tier, but hey, if you need more space you can always buy more. Creating backups of the important data is always a good idea and is relevant in 99% of any case. I've written a small script, which will archive the contents of your website and upload it automatically to your Google Drive.

Before we begin, we need to install prasmussen's Google Drive API CLI utility from https://github.com/prasmussen/gdrive. Navigate to the page and download gdrive-linux-x64 binary. Upload it to your server and then do the following:

mv gdrive-linux-x64 drive
mv drive /usr/local/sbin/
chmod +x /usr/local/sbin/drive

After your first attempt to upload or do anything with gdrive, you will be asked to link your Linux box with your Google Drive account. You will get a message like this:

Authentication needed
Go to the following url in your browser:
https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=367116221053-7n0vf5akrru7on602fjinrecfgoe78eg.apps.googleusercontent.com&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fdrive&state=state

You will need to verify your account by visiting this link in your browser while logged in to your Google Account and just authorize the application.

After that, we can prepare our script (it really doesn't matter where you put it though):

mkdir /root/scripts

And then create your script using the following source:

#!/bin/sh

#Our temporary backups will be arhived in this folder
TMPBACKUP='/root/tmp/'
#Website to backup (used only for naming purposes)
SITE='site.com'
#Directory that will be archived and backed up
BACKUPDIR='/home/site/public_html'
#Remote Google Drive directory ID where the file will be uploaded
ID='0B-1gCFNK7CAghmxnWEJaf2l3R00'

if [ ! -d "$TMPBACKUP" ]; then
        mkdir $TMPBACKUP
fi

cd $TMPBACKUP
#Archive the directory
tar -zcf "$SITE-$(date '+%Y-%m-%d').tar.gz" $BACKUPDIR

# upload to google drive and delete the source file
drive upload "$SITE-$(date '+%Y-%m-%d').tar.gz" --parent $ID --delete

Login to your Google Drive account and create your folder where your backups will be stored. You need to take note of your newly created folder (the ID will be displayed in your address bar when you are in it):

google-drive-folder-id

Open the above script and adjust the values per your need. Last thing we need to do after this is to setup an automated cron. In this example, we'll setup a cron which will take automatic backups at 12:00 each night:

SHELL="/bin/bash"
0 0 * * * /root/scripts/drive-backup.sh

Take note, that this is a very simple way to take daily snapshots of your site and upload it to your Google Drive account. It is not a good solution for big sites, but rather small and simple ones.

Comments