Automating Block Blob Backup

This post has been republished via RSS; it originally appeared at: Microsoft Tech Community - Latest Blogs - .

Introduction

Hi folks! My name is Felipe Binotto, Cloud Solution Architect, based in Australia.

 

This post is about how you can automate the backup of Block Blob Storage using Azure Backup Vault (not to be confused with Azure Recovery Service Vault). I specifically mention Block Blob because append and page blobs are not supported.

 

By automating the backup process of your Block Blob Storage, you can rest assured that your data is safe and secure in case of unexpected data loss.

 

Before we start, let us look at the solution’s high-level design.

 

High-Level Design

The following is a similar HLD (high-level design) I have done for a customer recently.

 

fbinotto_0-1678779519222.png

 

A few things to note from the above diagram:

 

  • The backup for Block Blobs is stored in the Storage Account, meaning there is no traffic flowing between the Storage Account and the Backup Vault. Therefore, all our Backup Vaults are on the Hub. We only need 1 Backup Vault per region.
  • The identity of the Backup Vault requires the Storage Account Backup Contributor role on the Storage Accounts that will be backed up.
  • We will use an Automation Account to automate the backup based on a tag on the Storage Account.
  • There is no schedule for the Backup policies because the backup is continuous. Only retention must be specified.
  • We will use REST API calls to create 2 different retention policies as you cannot set them from the portal.

 

Pre-Requisites

Before we begin, please ensure that you have the following prerequisites in place:

 

  • Azure Subscription
  • Automation Account
  • Storage Account
  • Backup Vault

 

High-Level Steps

The process of automating the backup of Block Blobs in the storage account can be broken down in a few steps, which we will go through in the following order:

 

  1. Create a User Assigned identity for your Automation Account
  2. Assigning the role of Backup Contributor for the identity
  3. Create Backup policies.
  4. Create a Runbook.

 

Getting Started

To start off, let us create a User Assigned Identity which we will assign to our Automation Account and grant the Backup Contributor role so that we can create the Backup policies.

 

$id = (New-AzUserAssignedIdentity -Name backupautomation -ResourceGroupName REPLACE_WITH_YOUR_RG –Location australiaeast).principalId

 

Now let us assign the Backup Contributor role to the identity.

 

New-AzRoleAssignment -ObjectId $id `
-RoleDefinitionName 'Backup Contributor' `
-Scope /subscriptions/<subscriptionId>

 

And assign the identity to the Automation Account.

 

# Get the automation account
$automationAccount = Get-AzAutomationAccount -ResourceGroupName REPLACE_WITH_YOUR_RG -Name REPLACE_WITH_YOUR_AA

# Assign the identity to the automation account
$automationAccount | Set-AzAutomationAccount -Identity $id

 

Next, we will create two Backup policies. One for our production environment which will have a retention of 30 days and another one for our non-production environment which will have a retention of 10 days.

 

First, we must create a payload with the policy details. We will start with the production policy.

 

$payload = @"
{
            "properties": {
                "datasourceTypes": [
                "Microsoft.Storage/storageAccounts/blobServices"
                ],
                "objectType": "BackupPolicy",
                "policyRules": [
                    {
                        "name": "Default",
                        "objectType": "AzureRetentionRule",
                        "isDefault": true,
                        "lifecycles": [
                        {
                        "deleteAfter": {
                        "duration": "P30D",
                        "objectType": "AbsoluteDeleteOption"
                        },
                        "sourceDataStore": {
                        "dataStoreType": "OperationalStore",
                        "objectType": "DataStoreInfoBase"
                        }
                    }
                ]
            }
        ]
    }
}
"@@

 

Now we can invoke the REST method to create the policy.

 

Invoke-AzRestMethod -SubscriptionId $MySubID -Method Put `
-ResourceProviderName "Microsoft.DataProtection/backupVaults/$vaultName /backupPolicies/$policyName" `
-ApiVersion 2021-01-01 -Payload $payload -ResourceGroupName $MyRG

 

Replace $MySubID with the subscription ID where the Backup Vault is located, replace $vaultName with your Backup Vault name, replace $policyName with the policy name you want (e.g., Production) and replace $MyRG with the Backup Vault resource group name.

Now let repeat the steps for non-production but change the duration in the $payload with value of “P10D”.

 

$payload = @"
{
            "properties": {
                "datasourceTypes": [
                "Microsoft.Storage/storageAccounts/blobServices"
                ],
                "objectType": "BackupPolicy",
                "policyRules": [
                    {
                        "name": "Default",
                        "objectType": "AzureRetentionRule",
                        "isDefault": true,
                        "lifecycles": [
                        {
                        "deleteAfter": {
                        "duration": "P10D",
                        "objectType": "AbsoluteDeleteOption"
                        },
                        "sourceDataStore": {
                        "dataStoreType": "OperationalStore",
                        "objectType": "DataStoreInfoBase"
                        }
                    }
                ]
            }
        ]
    }
}
"@@

 

Re-run the REST method but provide a different name for the $policyName (e.g., Non-Production)

 

Invoke-AzRestMethod -SubscriptionId $MySubID -Method Put `
-ResourceProviderName "Microsoft.DataProtection/backupVaults//$vaultName /backupPolicies/$policyName" `
-ApiVersion 2021-01-01 -Payload $payload -ResourceGroupName $MyRG

 

OK, now we are ready to create the Runbook which will automate the backup process.

 

#Ensures you do not inherit an AzContext in your runbook

Disable-AzContextAutosave -Scope Process

#Connect to Azure with user-assigned managed identity
Connect-AzAccount -Identity -AccountId #ReplaceWithYourIdentityID

#Set variables
$vaultName = #ReplaceWithYourVaultName
$resourceGroupName = #ReplaceWithYourRG

#Gets the list of all subscriptions
$subscriptions = Get-AzSubscription

$query = "resources | where type in~ ('microsoft.storage/StorageAccounts') | where tags.Environment != '' and location == 'australiaeast'"

$storages = Search-AzGraph -Subscription $subscriptions -Query $query

$query = "RecoveryServicesResources | where type in~ ('microsoft.DataProtection/backupVaults/backupInstances')"

$backups = Search-AzGraph -Subscription $subscriptions -Query $query

$npePolicy = Get-AzDataProtectionBackupPolicy -ResourceGroupName $resourceGroupName -VaultName $vaultName -Name "Non-Production"

$prdPolicy = Get-AzDataProtectionBackupPolicy -ResourceGroupName $resourceGroupName -VaultName $vaultName -Name "Production"

foreach ($storage in $storages) {

    $protected = $backups | Where-Object Name -match $storage.Name

    if (!$protected -or $protected.properties.currentProtectionState -ne "ProtectionConfigured") {

        $vault = Get-AzDataProtectionBackupVault -ResourceGroupName $resourceGroupName -VaultName $vaultName

        if ($storage.tags.Environment -eq "Non-Production") {

            $instance = Initialize-AzDataProtectionBackupInstance -DatasourceType AzureBlob -DatasourceLocation $vault.Location -PolicyId $npePolicy.id -DatasourceId $storage.ResourceId

            New-AzDataProtectionBackupInstance -ResourceGroupName $resourceGroupName -VaultName  $vaultName -BackupInstance $instance -NoWait
        }

        elseif ($storage.tags.Environment -eq "Production") {

            $instance = Initialize-AzDataProtectionBackupInstance -DatasourceType AzureBlob -DatasourceLocation $vault.Location -PolicyId $prdPolicy.id -DatasourceId $storage.ResourceId

            New-AzDataProtectionBackupInstance -ResourceGroupName $resourceGroupName -VaultName  $vaultName -BackupInstance $instance -NoWait

        }
        else {
            Write-Output "Invalid value provided for tag Environment. Values are: Non-Production or Production"
        }      
    }
}

 

A few values you must replace in the script above;

 

  • Replace #ReplaceWithYourIdentityID with the identity we created in an earlier step
  • Replace #ReplaceWithYourVaultName with the Backup Vault Name
  • Replace #ReplaceWithYourRG with the Resource Group of the Backup Vault

 

In addition, a few notes about the script;

 

  • We are only querying for Storage Accounts in the Australia East region. You could have a single automation account querying all regions, but I prefer this way to distribute the load
  • We are checking if the backup already exists for the retrieved Storage Accounts and if does, we do not do anything
  • We have defined the Tag name on the Storage Accounts to be Environment and the value to be either Production or Non-Production

 

Finally, as a last step, you can create the required tag in one of your Storage Accounts and run the runbook.

Once you are satisfied with the results, you can create a schedule for your Runbook and tag other Storage Accounts to automatically enable backup for Block Blobs.

 

Conclusion

In conclusion, automating the backup process of your Block Blob Storage is a crucial step in ensuring the safety and security of your data in case of unexpected data loss. By following the steps outlined in this post, you can set up an Azure Backup Vault to continuously back up your Block Blob Storage, without any traffic flowing between the Storage Account and the Backup Vault.

 

Additionally, creating an Automation Account, assigning the Backup Contributor role, and creating Backup policies can help simplify the backup process. Once you have completed these steps, you can easily run the Runbook to enable automatic backup for Block Blobs in your Storage Accounts.

 

Overall, this solution is a reliable and efficient way to ensure the safety of your data in the cloud.

 

I hope this was informative to you and thanks for reading!

 

 

Disclaimer

The sample scripts are not supported under any Microsoft standard support program or service. The sample scripts are provided AS IS without warranty of any kind. Microsoft further disclaims all implied warranties including, without limitation, any implied warranties of merchantability or of fitness for a particular purpose. The entire risk arising out of the use or performance of the sample scripts and documentation remains with you. In no event shall Microsoft, its authors, or anyone else involved in the creation, production, or delivery of the scripts be liable for any damages whatsoever (including, without limitation, damages for loss of business profits, business interruption, loss of business information, or other pecuniary loss) arising out of the use of or inability to use the sample scripts or documentation, even if Microsoft has been advised of the possibility of such damages.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

This site uses Akismet to reduce spam. Learn how your comment data is processed.