Automate Backup For Azure VMs Using PowerShell For Azure Backup

4 Min. Read

Introduction

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.

When you start preparing for Azure VMs backup, there are multiple settings 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.
  • Discover VMs, configure the backup policy.
  • Enable backup for Azure VMs.

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

One thing that you want to be aware of is, when you configure a backup policy in the Azure Portal to create your backup goal, you can attach a single backup policy to the VMs, it’s a one-to-one relationship. You cannot have multiple backup policies with different retention goals for the same virtual machine(s).

Automate Backup For Azure VMs Using PowerShell For Azure Backup 2

What if you want to take an additional backup (restore point) before a major update? for example, you have an update policy management that patches your servers at the end of every month at night. Now, of course, you can log in to the Azure Portal and take a manual backup by clicking Backup now for all virtual machines that are part of your update management cycle. However, this is not so efficient…

Automate Backup For Azure VMs Using PowerShell For Azure Backup 3

Azure Automation to the rescue!

In this blog, I will share with you how to automate the backup for Azure VMs using PowerShell so you can schedule it to take snapshots at regular intervals every week, month, or year in case you want to have an additional restore point before a major update.

Create an Azure Automation Account

First, I need to create an Azure automation resource with a Run As account. Run As accounts in Azure Automation are used to provide authentication for managing resources in Azure with the Azure cmdlets. When you create a Run As account, it creates a new service principal user in Azure Active Directory and assigns the Contributor role to this user at the subscription level.

Open the Azure portal, click All services found in the upper left-hand corner. In the list of resources, type Automation. As you begin typing, the list filters based on your input. Select Automation Accounts. Click +Add

Automate Backup For Azure VMs Using PowerShell For Azure Backup 4

Import Modules from Gallery

In the next step, you need to import the required modules from the Modules gallery.

In your list of Automation Accounts, select the account that you created in the previous step. Select Modules gallery under the Shared Resources section.

Automate Backup For Azure VMs Using PowerShell For Azure Backup 5

You need to import the following modules from the Modules gallery in the order given below:

  1. AzureRM.Profile
  2. AzureRM.RecoveryServices
  3. AzureRM.RecoveryServices.Backup

Automate Backup For Azure VMs Using PowerShell For Azure Backup 6

Create PowerShell Runbooks

In this step, you can create multiple Runbooks based on which set of Azure VMs you want to protect. PowerShell Runbooks are based on Windows PowerShell. You directly edit the code of the Runbook using the text editor in the Azure portal. You can also use any offline text editor and import the Runbook into Azure Automation.

In this example, I will create a Runbook to backup all Azure VMs in a specific Recovery Services Vault / Azure subscription and retain it for 30 days. You can also enable protection for specific VMs if you want.

Automate Backup For Azure VMs Using PowerShell For Azure Backup 7

Edit The Runbook

Once you have the Runbook created, you need to edit the Runbook, then write or add the script to choose which Azure File Share to take backup. Of course, you can create scripts that suit your environment.

As I mentioned earlier, in this example, I want to take a backup for all Azure VMs in a specific Recovery Services Vault / Azure subscription. The script as follows:

<#
.DESCRIPTION
A Runbook example that takes On-demand backup for all Azure VMs 
by Azure Backup in a specific Recovery Services Vaults / Azure subscription
using the Run As Account (Service Principal in Azure AD)

.NOTES
Filename   : Enable-AzureBackup
Author     : Charbel Nemnom
Version    : 1.1
Date       : 22-February-2019
Updated    : 20-April-2021

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

Param (
    [Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()]
    [String] $AzureSubscriptionId,
    [Parameter(Mandatory = $true)][ValidateNotNullOrEmpty()]
    [String] $vaultName,
    [Parameter(Mandatory = $false)][ValidateNotNullOrEmpty()]
    [Int] $RetentionDays = 14
)

$connectionName = "AzureRunAsConnection"

Try {
    #! Get the connection "AzureRunAsConnection "
    $servicePrincipalConnection = Get-AutomationConnection -Name $connectionName
    Write-Output "Logging in to Azure..."
    Add-AzureRmAccount -ServicePrincipal `
        -TenantId $servicePrincipalConnection.TenantId `
        -ApplicationId $servicePrincipalConnection.ApplicationId `
        -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
Catch {
    If (!$servicePrincipalConnection) {
        $ErrorMessage = "Connection $connectionName not found..."
        throw $ErrorMessage
    }
    Else {
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
}

Select-AzureRmSubscription -SubscriptionId $AzureSubscriptionId

$currentDate = Get-Date
$RetailTill = $currentDate.AddDays($RetentionDays)
Write-Output ("Recoverypoints will be retained till " + $RetailTill)

#! Set ARM vault resource
Write-Output ("Working on Vault: " + $vault)
$vault = Get-AzureRmRecoveryServicesVault -Name $vaultName
Set-AzureRmRecoveryServicesVaultContext -Vault $vault

$containers = Get-AzureRmRecoveryServicesBackupContainer -ContainerType AzureVM -Status Registered 
Write-Output ("Got # of Backup VM Containers: " + $containers.count)

ForEach ($container in $containers) {
    Write-Output ("Working on VM backup: " + $container.FriendlyName)
    $Item = Get-AzureRmRecoveryServicesBackupItem -Container $container -WorkloadType AzureVM 
    Backup-AzureRmRecoveryServicesBackupItem -Item $Item -ExpiryDateTimeUTC $RetailTill
}
Write-Output ("")

Save the script in the CMDLETS pane as shown in the following screenshot.

Automate Backup For Azure VMs Using PowerShell For Azure Backup 8

Then test the script using “Test Pane” to verify it’s working as intended before you publish it.

Automate Backup For Azure VMs Using PowerShell For Azure Backup 9

Once the test is completed, publish the Runbook by clicking Publish.

Schedule the Runbook

In the final step, you need to schedule the Runbook to run based on your desired backup policy.

Within the same Runbook that you create in the previous step, select Schedules and then click + Add schedule.

So, if you need to schedule a monthly snapshot that runs on the last Saturday, you need to create a monthly schedule as shown below. You can also create weekly, monthly and yearly snapshot (Recur every 12 Months) schedules in a similar manner. You can also modify the script to take input as a parameter in weeks/months/years as well.

Automate Backup For Azure VMs Using PowerShell For Azure Backup 10

While scheduling the Runbook, you can pass on the parameters required for the PowerShell Script. In my example, I need to specify the Azure Subscription ID, Vault Name, the Retention is set to 30 days (Default is 14 days). The sample script takes those parameters as input.

Automate Backup For Azure VMs Using PowerShell For Azure Backup 11

Once done, click OK.

Monitor the Runbook

You can monitor the success or failure of these backups using the “Jobs” tab of Runbooks under Resources. You can also see the next run schedule, in my example, the Runbook will run on March 30th, 2019, @ 12:00 PM and retain it for 30 days, and so forth…

Automate Backup For Azure VMs Using PowerShell For Azure Backup 12

That’s it there you have it!

Summary

In this article, I showed you how to automate the backup for Azure VMs using PowerShell so you can schedule it to take snapshots at regular intervals every week, month, or year for short or long term retention, and up to 9999 restore points if needed!

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

Speaking At The Global Azure Bootcamp Switzerland 2019 #GlobalAzure

Automate Azure Stack Infrastructure Backup Configuration With Certificate

Next

7 thoughts on “Automate Backup For Azure VMs Using PowerShell For Azure Backup”

Leave a comment...

  1. Thank you very much for the step by step process for enabling backup through Automation Account.
    Can you please help me on how to stop backup process and delete the data once the major change is completed successfully?

  2. Thank you Suresh for your comment,
    This is a custom request and cannot be covered here, if you are interested to work on this scenario, please feel free to contact me here.
    Thanks!

  3. Thanks for this documnet. Can you confirm how to use same run book but to take Backup only for particular VMs

  4. Thanks for your comment. Yes, this is possible. You could add a new parameter to the Runbook where you can add the list of all VMs that you want to protect, then adjust the loop where you enable the backup for each VM. Hope this helps!

  5. Thank You!

  6. Hi Charbel!
    Any idea how to set (passed\failed) notifications for these backup jobs?

  7. Hello Tamel, thanks for the comment. You can get the notifications for these backup jobs from the Recovery Services Vaults, Backup Jobs under the Monitoring section. You can also configure Backup Alerts to receive email notifications as well. Hope this helps!

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' by selecting the Code.

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

Thank you for visiting!