Forum Discussion

VivekChandran's avatar
VivekChandran
Copper Contributor
Sep 11, 2024

Automating Azure VM Snapshot Creation Across Subscriptions

Introduction

 

Managing virtual machines in Azure can be time-consuming, especially when creating snapshots across multiple subscriptions. Typically, this involves logging into the Azure portal, manually locating the VM, and creating snapshots for both the OS disk and attached data disks an inefficient and tedious process. To simplify this, I developed a PowerShell script that automates snapshot creation, allowing me to create snapshots by simply inputting the VM name. This script is part of my toolkit for automating repetitive Azure tasks. It iterates through all subscriptions linked to my Azure account, identifies the specified VM, and generates snapshots for both the OS and data disks within the VM’s resource group, adhering to a consistent naming convention. This article describes the script, the rationale behind its design, and how it improves the efficiency of managing Azure resources.
 

Design Considerations

When designing this script for automating Azure VM snapshot creation, several key considerations were prioritized to enhance efficiency and user experience:

 

1. Subscription Handling

All-Subscription Search: The script loops through all Azure subscriptions associated with the account. This design ensures that the script can locate the VM across any subscription without manual intervention to switch between them. This is particularly useful for environments with multiple subscriptions.

 

2. Dynamic VM Search

Automatic VM Discovery: Instead of requiring users to manually input resource group and subscription details, the script dynamically searches for the VM by its name across all subscriptions. This automation simplifies the process and reduces the likelihood of errors.

 

3. Snapshot Naming Convention

Consistent Naming Format: Snapshots are named using the format VMname_diskname_dd-MM-yyyy_HH_mm. This approach ensures that snapshots are well-organized and easily identifiable. The script also removes random characters, such as GUIDs, often appended to disk names, resulting in clean and consistent snapshot names.

 

4. OS and Data Disk Snapshots

Comprehensive Backup: The script separately handles snapshots for both the OS disk and data disks. This ensures that all disks attached to the VM are included in the backup process, providing complete coverage.

 

5. Time Efficiency

Streamlined Process: The script is designed to eliminate the need for repeated manual input and navigation within the Azure portal. By simply providing the VM name, users can automate the entire process, from VM identification to snapshot creation. This saves considerable time and effort, particularly in environments with many VMs and subscriptions.

By focusing on these design considerations, the script offers a robust and user-friendly solution for automating VM snapshot creation across Azure subscriptions.

 

Prerequisites

To use this script, you need:

  • Azure PowerShell module installed (Az module).
  • Active Azure account with sufficient permissions to access VMs and create snapshots across subscriptions.
  • A VM name as input.

 

Why Automate Snapshot Creation?

In many organizations, virtual machines (VMs) are critical for running services, and regularly creating snapshots of these VMs is essential for disaster recovery and version control. Traditionally, creating snapshots for Azure VMs involves several manual steps:

  1. Log in to the Azure Portal: Access the Azure portal to start the snapshot creation process.
  2. Navigate Through Subscriptions: Switch between different Azure subscriptions to find the correct VM.
  3. Locate the Correct VM: Search for and select the specific VM for which you want to create snapshots.
  4. Create Snapshots: Manually create snapshots for both the OS disk and any attached data disks.
  5. Repeat the Process: Perform these steps for each disk across multiple VMs or subscriptions.

This manual process is not only time-consuming but also prone to errors. Automating snapshot creation simplifies and streamlines the process:

  • Reduces Manual Effort: The entire process can be accomplished with a few clicks.
  • Saves Time: Automation eliminates the need to repeat steps across multiple VMs and subscriptions.
  • Minimizes Errors: By automating the process, you reduce the risk of human error.

With the automation script, you only need to provide the VM name, and the script handles the rest, making snapshot management more efficient and reliable.

 

Script Overview

Below is the PowerShell script that automates the process of creating snapshots for a VM across multiple subscriptions in Azure:

<#
.SYNOPSIS
    This script automates the process of creating snapshots for a virtual machine (VM) in Azure across multiple subscriptions.
    The script will locate the VM by its name, determine the resource group where it exists, and create snapshots for both the
    OS disk and any attached data disks. It ensures that the snapshot names follow a specific naming convention while removing
    any random characters appended to the disk names.

.DESCRIPTION
    - Loops through all Azure subscriptions attached to the account.
    - Searches for a specified VM by name across all subscriptions.
    - Identifies the resource group of the VM.
    - Creates snapshots for the OS disk and all data disks in the same resource group as the VM.
    - Follows the snapshot naming convention: computername_diskname_dd-mm-yyyy_hh_mm.
    - Removes random characters (e.g., GUIDs) after the disk name in snapshot naming.

.NOTES
    Author: Vivek Chandran
    Date Created: 11-09-2023


#>

# Login to Azure (if not already logged in)
Connect-AzAccount

# Prompt the user to enter the VM name
$computerName = Read-Host -Prompt "Please enter the name of the VM you want to snapshot"

# Get all subscriptions available to the account
$subscriptions = Get-AzSubscription

# Loop through each subscription to find the specified VM
foreach ($subscription in $subscriptions) {
    # Set the subscription context so that all subsequent commands target this subscription
    Set-AzContext -SubscriptionId $subscription.Id

    # Retrieve all VMs in the current subscription
    $vms = Get-AzVM

    # Check if a VM with the specified name exists in this subscription
    $vm = $vms | Where-Object { $_.Name -eq $computerName }

    if ($vm) {
        # Output message indicating the VM was found
        Write-Host "VM '$computerName' found in subscription '$($subscription.Name)'"

        # Retrieve the resource group where the VM resides
        $resourceGroup = $vm.ResourceGroupName

        # Loop through each data disk attached to the VM and create a snapshot
        foreach ($disk in $vm.StorageProfile.DataDisks) {
            # Get the name of the data disk
            $diskName = $disk.Name

            # Remove any random characters from the disk name after the first underscore (if present)
            $cleanedDiskName = ($diskName -split '_')[0..1] -join '_'

            # Get the current date and time in the format 'dd-MM-yyyy_HH_mm' for use in the snapshot name
            $currentDateTime = Get-Date -Format 'dd-MM-yyyy_HH_mm'

            # Construct the snapshot name using the cleaned disk name and the date/time
            $snapshotNameWithDataDisk = "$computerName-$cleanedDiskName-$currentDateTime"

            # Define the snapshot configuration using the disk's managed disk ID
            $snapshotConfig = New-AzSnapshotConfig -SourceUri $disk.ManagedDisk.Id -Location $vm.Location -CreateOption Copy -AccountType Standard_LRS

            # Create the snapshot in the same resource group as the VM
            New-AzSnapshot -Snapshot $snapshotConfig -ResourceGroupName $resourceGroup -SnapshotName $snapshotNameWithDataDisk

            # Output message indicating that the snapshot was successfully created for the data disk
            Write-Host "Snapshot created for data disk: $snapshotNameWithDataDisk"
        }

        # Create a snapshot for the OS disk of the VM
        $osDisk = $vm.StorageProfile.OsDisk

        # Get the name of the OS disk
        $osDiskName = $osDisk.Name

        # Remove any random characters from the OS disk name after the first underscore (if present)
        $cleanedOsDiskName = ($osDiskName -split '_')[0..1] -join '_'

        # Get the current date and time in the format 'dd-MM-yyyy_HH_mm' for use in the snapshot name
        $currentDateTime = Get-Date -Format 'dd-MM-yyyy_HH_mm'

        # Construct the snapshot name using the cleaned OS disk name and the date/time
        $snapshotNameWithOSDisk = "$computerName-$cleanedOsDiskName-$currentDateTime"

        # Define the snapshot configuration using the OS disk's managed disk ID
        $snapshotConfig = New-AzSnapshotConfig -SourceUri $osDisk.ManagedDisk.Id -Location $vm.Location -CreateOption Copy -AccountType Standard_LRS

        # Create the snapshot in the same resource group as the VM
        New-AzSnapshot -Snapshot $snapshotConfig -ResourceGroupName $resourceGroup -SnapshotName $snapshotNameWithOSDisk

        # Output message indicating that the snapshot was successfully created for the OS disk
        Write-Host "Snapshot created for OS disk: $snapshotNameWithOSDisk"

        # Exit the loop since the VM has been found and processed
        break
    } else {
        # Output message indicating that the VM was not found in this subscription
        Write-Host "VM '$computerName' not found in subscription '$($subscription.Name)'"
    }
}

# Output a final message indicating that the snapshot process has completed
Write-Host "Snapshots process completed!"

 

How the Script Works

 

1. Azure Authentication

  • Connect to Azure: The script starts by authenticating the user to Azure using the Connect-AzAccount command. If the user is already logged in, this step is skipped.

 

2. Input the VM Name

  • Prompt for VM Name: After successful authentication, the script prompts you to enter the name of the virtual machine (VM) you want to create snapshots for.

 

3. Subscription Looping

  • Retrieve Subscriptions: The script retrieves all Azure subscriptions associated with the account using Get-AzSubscription.
  • Check Each Subscription: It iterates through each subscription to check if the specified VM exists. When the VM is found, the script switches the context to that subscription using Set-AzContext.

 

4. Snapshot Creation

  • Data Disk Snapshots: For each data disk attached to the VM, the script creates a snapshot. It follows a consistent naming convention that includes the VM name, disk name, and timestamp to ensure clarity and organization.
  • OS Disk Snapshot: After handling the data disks, the script creates a snapshot for the OS disk, using the same naming convention.

 

5. Completion

  • Confirmation Message: Once all snapshots (for both OS and data disks) are created, the script outputs a message confirming the successful completion of the snapshot creation process.

 

Conclusion

This PowerShell script has greatly improved my workflow for managing Azure VMs. By automating the snapshot creation process, it eliminates the need to manually log into the Azure portal, locate the VM, and create snapshots for each disk individually. Instead, I can simply run the script, provide the VM name, and let it handle the entire process.

For anyone managing multiple Azure subscriptions and seeking a reliable method to automate snapshot creation, this script offers a quick and effective solution. It ensures that backups are created consistently and stored properly, enhancing overall backup management and efficiency.

No RepliesBe the first to reply

Resources