Set your Azure WebApps backup schedule with Powershell

Recently I received a task to set Azure WebApps backup schedule.
In normal way it will require to create storage account, containers for each application and Storage Access signature for each container.
Until all prerquisites are not met we can’t set schedule on application.
Hopefully we’ve got Powershell which is also usefull in this case.
All work (including all prerequisites) can be done with one script.
Below you can find how to set backup schedule for all of your WebApps 🙂

$Customer = "TestCustomer"
$StorageAccountRG = "rg_backup_test"
$StorageAccountName = ($Customer+"backupaccount").ToLower()

Try
{
    # Create resource group for backup storage account
    New-AzureRmResourceGroup -Name $StorageAccountRG -Location WestEurope -Force
    # Create storage account for webapps backup
    $NewStorageAccount = New-AzureRmStorageAccount -Name $StorageAccountName -ResourceGroupName $StorageAccountRG -SkuName Standard_LRS -Location WestEurope
}
Catch
{
    $Exc = $_.Exception.Message
}

if($exc -eq $null)
{

    $WebApps = Get-AzureRMWebApp
    $WebApps = $WebApps | select SiteName, ResourceGroup

    foreach($webapp in $WebApps)
    {
        $WebAppName = $webapp.SiteName
        $RG = $webapp.ResourceGroup
        $WebAppBackupContainer = $WebAppName

        # Get storage context
        $StorageAccountKey = (Get-AzureRmStorageAccountKey -ResourceGroupName $StorageAccountRG -Name $StorageAccountName).Value[0]
        $Context = New-AzureStorageContext -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey
        # Create container for specific webapp
        New-AzureStorageContainer -Name $WebAppBackupContainer -Context $Context

        ### Generate SAS token
        $SASToken = New-AzureStorageContainerSASToken -Name $WebAppBackupContainer  -Permission rwdl -Context $Context -FullUri -ExpiryTime (Get-Date).AddYears(30)
        # Configure backup scheduler
        Edit-AzureRmWebAppBackupConfiguration -FrequencyInterval 24 -FrequencyUnit Hour -RetentionPeriodInDays 30 -StartTime (Get-Date).AddHours(5) -Name $WebAppName -ResourceGroupName $RG -StorageAccountUrl $SASToken -KeepAtLeastOneBackup
    }
}

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.