Create snapshots of Azure managed disks

You know the old saw about scripting anything you do more than once? That’s what lead me to create the PowerShell script below that snapshots managed disks attached to an Azure VM. Of special note: I tested this on a Mac running pwsh 6 with the AzureRm.NetCore cmdlets. It works on Windows PowerShell as well, of course.

The script assumes:

  • Your VM is using Azure managed disks.
  • You want to create snapshots for the OS disk (there is only one) and all data disks.
  • You are happy to have the snapshots in the same resource group as the disks themselves.
  • It’s OK to stop/deallocate your VM. If you don’t, you can’t be sure of the state of the volumes and the snapshots may not be consistent. The script checks the state of the VM and if it’s running, stops it before creating any snapshots.
  • You have a saved context for authorization. See Enable-AzureRmContextAutosave.

If that works for you, this script will create Azure managed disk snapshots with a consistent name, which unfortunately has to be truncated to 63 characters — the limit on these names.

The data disk snapshots are created using the -AsJob parameter to speed everything up. The script issues Get-Job | Wait-Job | Receive-Job so that you can tell when everything is done. But it doesn’t otherwise do anything with the job output.

I hope you find this useful. It’s a little harder, IMO, to create usable images in Azure than is to create an AWS EC2 AMI. And there’s lots this script could do, like tag the snapshots, that I’ll leave to you.

I hope this helps you. I’d welcome any feedback you might have.

<#?    .SYNOPSIS?        For a single Azure VM using managed disks, stops the VM and creates snapshots of all disks, storing them in the same region and resource group as the VM?    ?    .EXAMPLE?    .\CreateSnapshotsFromAzureVmManagedDisks -VM [string] -ResourceGroup [string] -Location [string] -AzureContext [string]?    ?    .DESCRIPTION?        Creates snapshots of the a VM's managed disks. There's always only one OsDisk and but there can be multiple data disks in the VM?    ?    .PARAMETER VM?        Name of the VM?    ?    .PARAMETER ResourceGroup?        Resource group containing the VM. Snapshots are placed in the same RG?    ?    .PARAMETER Location?        Region containing all disks: the VM, the volumes and the snapshots?    ?    .PARAMETER AzureContext?        A saved Azure context (see Enable-AzureRmContextAutosave) which points to the correct account and subscription?    ?    .NOTES?        Alex Neihaus 2018-03-23?        (c) 2018 Air11 Technology LLC -- licensed under the Apache OpenSource 2.0 license, https://opensource.org/licenses/Apache-2.0?        Licensed under the Apache License, Version 2.0 (the "License");?        you may not use this file except in compliance with the License.?        You may obtain a copy of the License at?        http://www.apache.org/licenses/LICENSE-2.0? ?        Unless required by applicable law or agreed to in writing, software?        distributed under the License is distributed on an "AS IS" BASIS,?        WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.?        See the License for the specific language governing permissions and?        limitations under the License.? ?        Author's blog: https://yobyot.com?#>?param?(?    [Parameter(Mandatory = $true)]?    [string]$VM,?    [Parameter(Mandatory = $true)]?    [string]$ResourceGroup,?    [Parameter(Mandatory = $true)]?    [string]$AzureContext = 'YourSavedAzureRmContext',?    [Parameter(Mandatory = $false)]?    [string]$Location = "eastus"?)?#Import-Module AzureRm.NetCore -MinimumVersion 0.10.0?#Import-Module AzureRM -MinimumVersion 5.5.0??Set-AzureRmContext $AzureContext # Presumes a saved context for the proper account & subscription??$VmStatus = Get-AzureRmVM -Status -Name $VM -ResourceGroupName $ResourceGroup?foreach ($Status in $VmStatus.Statuses)?{?    if ($Status.Code -eq "PowerState/running")?    {?        Write-Host "$VM status $($Status.Code)" -ForegroundColor Yellow?        $Continue = Read-Host "Need to stop/deallocate $VM; Are you sure? Enter y to continue"?        if ($Continue.ToLower() -ne 'y')?        {?            Write-Host "$VM cannot be snapshotted while running" -ForegroundColor Yellow?            "Exiting"?            exit?        }?        "Stopping $VM"?        Stop-AzureRmVM -Name $VM -ResourceGroupName $ResourceGroup -Force?    }?}??$OsDiskName = (Get-AzureRmVM -Name $VM -ResourceGroupName $ResourceGroup).StorageProfile.OSDisk.Name # There is always just one OsDisk?$OsDiskId = (Get-AzureRmDisk -Name $OsDiskName -ResourceGroupName $ResourceGroup).Id?$OsDiskSnapshotConfig = New-AzureRmSnapshotConfig -SourceUri $OsDiskId -Location $Location -CreateOption "Copy"?$SnapshotName = $((Get-Date -Format s).Replace(":", "-") + "-$VM" + "-Snapshot-" + $OsDiskName )?If ($SnapshotName.Length -ge 63)?{?    $SnapshotName = $SnapshotName.Substring(0, 63)?}?New-AzureRmSnapshot -Snapshot $OsDiskSnapshotConfig -SnapshotName $SnapshotName -ResourceGroupName $ResourceGroup??$DataDisks = (Get-AzureRmVM -Name $VM -ResourceGroupName $ResourceGroup).StorageProfile.DataDisks.Name # There might be a collection of data disks?foreach ($DataDisk in $DataDisks)?{?    $DataDiskID = (Get-AzureRmDisk -Name $DataDisk -ResourceGroupName $ResourceGroup).Id?    $DataDiskSnapshotConfig = New-AzureRmSnapshotConfig -SourceUri $DataDiskID -Location $Location -CreateOption "Copy"?    $SnapshotName = $((Get-Date -Format s).Replace(":", "-") + "-$VM" + "-Snapshot-" + $DataDisk )?    If ($SnapshotName.Length -ge 63)?    {?        $SnapshotName = $SnapshotName.Substring(0, 63)?    }?    New-AzureRmSnapshot -Snapshot $DataDiskSnapshotConfig -SnapshotName $SnapshotName -ResourceGroupName $ResourceGroup -AsJob?}??Get-Job | Wait-Job | Receive-Job?"Snapshots for $VM Complete"

 


Posted

in

, , ,

by

Comments

2 responses to “Create snapshots of Azure managed disks”

  1. Ron Avatar
    Ron

    Outstanding job.  I have searched for info about snapshotting data disks with PowerShell, and all other posts demo snapshotting the OS disk and call themselves done.  This is the only complete post that includes how to handle data disks.  Thank you!

    1. Alex Neihaus Avatar
      Alex Neihaus

      Thank you, Ron. I’m glad this was useful for you.

Leave a Reply

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