Create Azure Backup Protection Policy With PowerShell

6 Min. Read

Azure Backup is the Azure-based service you can use to back up (or protect) and restore your data in the Microsoft cloud. Azure Backup replaces your existing on-premises or off-site backup solution with a cloud-based solution that is reliable, secure, and cost-competitive.

In this article, I will share with you how to automate the creation of Azure backup protection policy with PowerShell.

Introduction

When you start preparing to protect your workloads with Azure backup, there are multiple prerequisites you want to verify such as:

  • Verify supported scenarios and prerequisites.
  • Install the Azure VM agent if needed, and verify outbound access for VMs.
  • Create a Recovery Services Vault.
  • Set up storage for the vault (Local-Redundant or Geo-Redundant).
  • Create and configure the backup policy based on your company policy.
  • Enable backup.

You can read about all the prerequisites and preparation in the following article.

When you plan to create and configure a backup policy in the Azure Portal, you need to specify the policy type such as (Azure Virtual Machine, Azure File Share, SQL Server in Azure VM, or SAP HANA in Azure VM) to create the backup goal. Then when you choose the backup type, you have to set the backup schedule and retention range (daily, weekly, monthly, or yearly), and optionally in the case of Azure IaaS VM, you need to set the Azure Backup resource group name to store the instant recovery points of managed virtual machines according to your company’s naming convention.

Create Azure Backup Policy in the Portal

What if you want to create several backup policies and each policy for a specific workload with a different retention range? for example, let’s say your company has a backup policy defined for each application to meet their regulatory compliance (E.g. Application A = daily for x number of days, weekly for x number of weeks, monthly for x number of months, and yearly for x number of years). Now, of course, you can log in to the Azure Portal and create those backup policies and follow the wizard. However, this is not so efficient…

Automation to the rescue!

In this article, I will share with you how to automate the creation of the Azure backup policies with PowerShell.

Prerequisites

To follow this guide, you need to have the following:

  1. Azure subscription – If you don’t have an Azure subscription, you can create a free one here.
  2. Azure Resource Group obviously.
  3. Azure Recovery Services Vault already created.
  4. The Azure PowerShell (Az module) installed locally on your machine. You can use the following PowerShell command to install and update the “Az module”.
# Make sure you have the latest version of PowerShellGet installed
Install-Module -Name PowerShellGet -Force

# Install and update to the latest Az PowerShell module
Install-Module -Name Az -AllowClobber -Force

Assuming you have all the prerequisites in place, run the following PowerShell tool.

Create Azure Backup Protection Policy

You have a couple of options to run this tool, you can either use Azure Cloud Shell, Visual Studio Code, or the new Windows Terminal. The Script works with PowerShell 5.1 or PowerShell 7 with the Az module installed.

.EXAMPLE

.\New-AzBackupProtectionPolicy.ps1 -BackupPolicyName [PolicyName] -WorkloadType [WorkloadType] `
      -SubscriptionName [AzureSubscriptionName] -$RSVaultName [RecoveryServicesVaultName]  `
      -BackupRGPrefix [BackupRGName] -WeeklyBackup [Yes] -MonthlyBackup [Yes] -YearlyBackup [No]

This example will create a new backup policy depending on the workload that you specified, for version 1.0 of this tool, you can create a backup policy for (Azure VM, Azure Files, or SQL Server in Azure VM) as workload type. You need to specify the desired Azure subscription and the Recovery Services Vault name where you want to create the policy. Optionally, you can specify the Azure Backup Resource Group prefix name where you want to store the instant recovery points of your virtual machines according to your company requirements (naming convention).

You can also enable weekly, monthly, or yearly retention policy by setting the switch to ‘YES‘. If you don’t set them, the default policy is set to ‘No‘. In this example, I have enabled weekly, monthly retention, and disabled the yearly backup. By default, the daily retention backup point is always enabled according to Azure Backup policy.

When you run this tool, you need to authenticate with your Azure account assuming you have the right RBAC permissions to manage backup policies in your environment. Then you will be prompted to set the daily backup point, the weekly backup point, the monthly backup point values, etc.

PowerShell Code

The complete script is detailed below to automate the entire creation process of the Azure backup policy:

<#
.SYNOPSIS
Create Azure Backup Protection Policy with PowerShell.

.DESCRIPTION
Create Azure Backup Protection Policy with PowerShell for Azure VM, Azure Files, and SQL Server in Azure VM.

.NOTES
File Name : New-AzBackupProtectionPolicy.ps1
Author    : Charbel Nemnom
Twitter   : @CharbelNemnom
Date      : 22-Mar-2021
Updated   : 23-Mar-2021
Version   : 1.0
Requires  : PowerShell Az and Az.RecoveryServices Module
Disclaimer: This script is provided "AS IS" with no warranties

.LINK
To provide feedback or for further assistance,
Please leave a comment below.

.EXAMPLE
.\New-AzBackupProtectionPolicy.ps1 -BackupPolicyName [PolicyName] -WorkloadType [WorkloadType] `
     -SubscriptionName [AzureSubscriptionName] -$RSVaultName [RecoveryServicesVaultName]  `
     -BackupRGPrefix [BackupRGName] -WeeklyBackup [Yes] -MonthlyBackup [Yes] -YearlyBackup [Yes]

This example will create a new backup policy depending on the workload that you specified, for version 1.0 of this tool,
You can create a backup policy for (Azure VM, Azure Files, or SQL Server in Azure VM) as workload type.
You need to specify the desired Azure subscription and the Recovery Services Vault name where you want to create the policy.
Optionally, you can specify the Azure Backup Resource Group prefix name where you want to store the instant recovery points of your virtual machines.
You can also enable weekly, monthly, or yearly retention policy by setting the switch to 'YES'.
In this example, I have enabled weekly, monthly retention, and disabled the yearly backup.
By default, the daily retention backup point is always enabled according to Azure Backup policy.
#>

[CmdletBinding()]
param(
    [Parameter(Mandatory=$true, HelpMessage='Backup Policy Name')]
    [ValidateNotNullOrEmpty()]
    [Alias('PolicyName')]
    [String]$BackupPolicyName,

    [Parameter(Mandatory=$true, HelpMessage='Azure Subscription Name')]
    [ValidateNotNullOrEmpty()]
    [Alias('AzSubscriptionName')]
    [String]$SubscriptionName,

    [Parameter(Mandatory=$true, HelpMessage='Recovery Services Vault Name')]
    [ValidateNotNullOrEmpty()]
    [Alias('VaultName')]
    [String]$RSVaultName,

    [Parameter(Mandatory=$false, HelpMessage='Azure Backup RG Prefix Name to store instant recovery points for Azure VMs')]
    [ValidateNotNullOrEmpty()]
    [Alias('RGPrefix')]
    [String]$BackupRGPrefix,

    [ValidateSet("AzureVM", "AzureFiles", "MSSQL")]
    [String]$WorkloadType='AzureVM',

    [ValidateSet("Yes","No")]
    [String]$WeeklyBackup='No',

    [ValidateSet("Yes","No")]
    [String]$MonthlyBackup='No',

    [ValidateSet("Yes","No")]
    [String]$YearlyBackup='No'
 )

#! Login with Connect-AzAccount if NOT using Cloud Shell
#! Check Azure Connection
Try {
    Write-Verbose "Connecting to Azure Cloud..."
    Connect-AzAccount -ErrorAction Stop -WarningAction SilentlyContinue | Out-Null
}
Catch {
    Write-Warning "Cannot connect to Azure Cloud. Please check your credentials. Exiting!"
    Break
}

#! Set Azure Subscription Context
Try {
    Write-Verbose "Setting Azure Context - Subscription Name: $SubscriptionName..."
    $azSub = Get-AzSubscription -SubscriptionName $SubscriptionName
    Set-AzContext $azSub.id | Out-Null
}
Catch {
    Write-Warning "Cannot set Azure context. Please check your Azure subscription name. Exiting!"
    Break
}

Write-Verbose "Getting a Base Backup Schedule Policy object..."
$SchPol = Get-AzRecoveryServicesBackupSchedulePolicyObject -WorkloadType $WorkloadType
$SchPol.ScheduleRunTimes.Clear()
$Dt  = Get-Date
$Dt1 = Get-Date -Year $Dt.Year -Month $Dt.Month -Day $Dt.Day -Hour $Dt.Hour -Minute 0 -Second 0 -Millisecond 0
Write-Verbose "Setting Backup Policy Schedule in UTC Timezone: $($dt1.ToUniversalTime())"
$SchPol.ScheduleRunTimes.Add($Dt1.ToUniversalTime())
Write-Verbose "Getting a Base Backup Retention Policy object..."
$RetPol = Get-AzRecoveryServicesBackupRetentionPolicyObject -WorkloadType $WorkloadType

If ($WorkloadType -eq "AzureVM" -or $WorkloadType -eq "MSSQL") {
    Do {
        [Int]$DailyRetention = Read-Host "Enter Daily backup point for $WorkloadType - value must be between 7 and 9999"
    } while ($DailyRetention -lt 7 -or $DailyRetention -gt 9999)
}

If ($WorkloadType -eq "AzureFiles") {
    Do {
        [Int]$DailyRetention = Read-Host "Enter Daily backup point for $WorkloadType - value must be between 1 and 200"
    } while ($DailyRetention -lt 1 -or $DailyRetention -gt 200)
}

Write-Verbose "Set Daily Schedule for $DailyRetention days..."
$RetPol.DailySchedule.DurationCountInDays = $DailyRetention

If ($WeeklyBackup -eq "Yes") {
    If ($WorkloadType -eq "AzureVM" -or $WorkloadType -eq "MSSQL") {
        Do {
            [Int]$WeeklyBackup = Read-Host "Enter Weekly backup point for $WorkloadType - value must be between 1 and 5163"
        } while ($WeeklyBackup -lt 1 -or $WeeklyBackup -gt 5163)
    }

    If ($WorkloadType -eq "AzureFiles") {
        Do {
            [Int]$WeeklyBackup = Read-Host "Enter Weekly backup point for $WorkloadType - value must be between 1 and 200"
        } while ($WeeklyBackup -lt 1 -or $WeeklyBackup -gt 200)
    }

    Write-Verbose "Set Weekly Schedule for $WeeklyBackup weeks..."
    $RetPol.WeeklySchedule.DurationCountInWeeks = $WeeklyBackup
}
Else {
    $RetPol.WeeklyScheduleEnabled = $false
}

If ($MonthlyBackup -eq "Yes") {
    If ($WorkloadType -eq "AzureVM" -or $WorkloadType -eq "MSSQL") {
        Do {
            [Int]$MonthlyBackup = Read-Host "Enter Monthly backup point for $WorkloadType - value must be between 1 and 1188"
        } while ($MonthlyBackup -lt 1 -or $MonthlyBackup -gt 1188)
    }

    If ($WorkloadType -eq "AzureFiles") {
        Do {
            [Int]$MonthlyBackup = Read-Host "Enter Monthly backup point for $WorkloadType - value must be between 1 and 200"
        } while ($MonthlyBackup -lt 1 -or $MonthlyBackup -gt 200)
    }

    Write-Verbose "Set Monthly Schedule for $MonthlyBackup months..."
    $RetPol.MonthlySchedule.DurationCountInMonths = $MonthlyBackup
}
Else {
    $RetPol.IsMonthlyScheduleEnabled = $false
}

If ($YearlyBackup -eq "Yes") {
    If ($WorkloadType -eq "AzureVM" -or $WorkloadType -eq "MSSQL") {
        Do {
            [Int]$YearlyBackup = Read-Host "Enter Yearly backup point for $WorkloadType - value must be between 1 and 99"
        } while ($YearlyBackup -lt 1 -or $YearlyBackup -gt 99)
    }

    If ($WorkloadType -eq "AzureFiles") {
        Do {
            [Int]$YearlyBackup = Read-Host "Enter Yearly backup point for $WorkloadType - value must be between 1 and 10"
        } while ($YearlyBackup -lt 1 -or $YearlyBackup -gt 10)
    }

    Write-Verbose "Set Yearly Schedule for $YearlyBackup years..."
    $RetPol.YearlySchedule.DurationCountInYears = $YearlyBackup
}
Else {
    $RetPol.IsYearlyScheduleEnabled = $false
}

Try {
    Write-Verbose "Getting the existing Azure Recovery Services Vault..."
    $vault = Get-AzRecoveryServicesVault -Name $RSVaultName
    Write-Verbose "Setting Azure Recovery Services Vault Context..."
    Set-AzRecoveryServicesVaultContext -Vault $vault -ErrorAction Stop -WarningAction SilentlyContinue
}
Catch {
    Write-Warning "Cannot set Azure Recovery Services Vault Context. Please check your Azure Recovery Services Vault name. Exiting!"
    Break
}

Write-Verbose "Creating Azure Backup Protection Policy..."
$ProtectionPolicy = New-AzRecoveryServicesBackupProtectionPolicy -Name $BackupPolicyName `
 -WorkloadType $WorkloadType -RetentionPolicy $RetPol -SchedulePolicy $SchPol

If ($WorkloadType -eq "AzureVM" -and $BackupRGPrefix -ne $null) {
    $Pol = Get-AzRecoveryServicesBackupProtectionPolicy -Name $BackupPolicyName
    $Pol.AzureBackupRGName = $BackupRGPrefix
    Write-Verbose "Adding resource group name prefix to stores the instant restore points..."
    Set-AzRecoveryServicesBackupProtectionPolicy -Policy $Pol
    $ProtectionPolicy = Get-AzRecoveryServicesBackupProtectionPolicy -Name $BackupPolicyName
    Write-Output $ProtectionPolicy | Select-Object Name, WorkloadType, AzureBackupRGName, SnapshotRetentionInDays -ExpandProperty RetentionPolicy
}
Else {
    Write-Output $ProtectionPolicy | Select-Object Name, WorkloadType, SnapshotRetentionInDays -ExpandProperty RetentionPolicy
}

Here is how to run this tool in action:

If you look back in the Azure Portal under your Recovery Services Vault, you will see the Azure Backup Policy is created successfully with the chosen retention range.

That’s it there you have it. Happy Azure Backup Policy Creation!

Summary

In this article, I showed you how to automate the creation of Azure Backup Protection policies with PowerShell. Now, of course, you can use Azure CLI, ARM Templates, Bicep, or Terraform to do the same, however, I prefer to use Azure PowerShell.

This is version 1.0, if you have any feedback or changes that everyone should receive, please feel free to leave a comment below.

Do you want to explore the Azure Backup service in a deeper way, diving into the finer details of how things work, and helping people understand where it differs from what we traditionally used to do in the backup world? I highly recommend checking Azure Backup Deep Dive – Free Whitepaper.

__
Thank you for reading my blog.

If you have any questions or feedback, please leave a comment.

-Charbel Nemnom-

Related Posts

Previous

Celebrate World Backup Day 2021 and WIN With @AltaroSoftware

Use Azure VPN Gateway To Route Traffic Between Spoke Networks

Next

Let me know what you think, or ask a question...

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

Subscribe to Stay in Touch

Never miss out on your favorite posts and our latest announcements!

The content of this website is copyrighted from being plagiarized! You can copy from the 'Code Blocks' in Black.

Please send your feedback to the author using this form for any 'Code' you like.

Thank you for visiting!

ads