Azure Storage Tables: Backing up your tables!
Written by Kevin Saye:
This blog shows how, using PHP, we can backup Azure Storage Tables to another storage account and a different table.
While there are solutions out there (http://tablestoragebackup.codeplex.com/) that can help with backing up Azure Tables, why not just copy the contents to another Storage Table? Because Azure Storage is inexpensive, compared to disk storage and bandwidth, this makes perfect sense.
Sadly, there is not a PowerShell command to clone Azure Tables, like there is for Azure Blob Storage. To resolve this, we can simply iterate through the Table entries and insert them to another storage account. Using a simple PHP file (shown below) and a Web Job, we can set this up in a matter of minutes and have peace of mind that, should something happen, we have a clone of our date. I schedule my Web Job daily.
In the file below, you see that we select all entries from the “$tableName” with no filter. We use the ConnectionString for the source table, and to simplify things, I just include the new Storage Account in the variable “$backupStorageAcct”.
This solution requires the Azure SDK for PHP, which can be downloaded here: Azure SDK for PHP.
PHP File:
<?php
require_once 'vendor\autoload.php';
use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Common\ServiceException;
use WindowsAzure\Table\Models\Entity;
use WindowsAzure\Table\Models\EdmType;
$backupStorageAcct = "DefaultEndpointsProtocol=https;AccountName=%AccountNameRemoved%;AccountKey=%AccountKeyRemoved%";
$tableRestProxy = ServicesBuilder::getInstance()->createTableService($_SERVER["CUSTOMCONNSTR_StorageAccount"]);
$tableRestProxyBack = ServicesBuilder::getInstance()->createTableService($backupStorageAcct);
$tableName = "%YourTableNameHere%";
$today = new DateTime();
$today = $today->format("mdY");
$backuptablename = $tableName . "backup" . $today;
createTable();
backupTable();
#To do: Delete old tables?
function backupTable() {
global $tableName, $tableRestProxy, $tableRestProxyBack, $backuptablename;
$filter = "";
echo "Backing up table $tableName<br>";
try {
$result = $tableRestProxy->queryEntities($tableName, $filter);
}
catch(ServiceException $e){
echo $code.": ".$e->getMessage()."<br />";
}
$entities = $result->getEntities();
foreach($entities as $entity){
$tableRestProxyBack->insertEntity($backuptablename, $entity);
echo ".";
}
}
function createTable() {
global $backuptablename, $tableRestProxyBack;
echo "Creating table $backuptablename<br>";
try {
$tableRestProxyBack->createTable($backuptablename);
}
catch(ServiceException $e){
echo $code.": ".$e->getMessage()."<br />";
}
}
?>