来分享一个批量给所有虚机创建快照的脚本,这个虽然不难,不过还是比较实用的,脚本的效果就是给某个资源组下的所有虚机,都创建一个快照出来,包括虚机的OS盘以及数据盘都会打一个快照,这在做某些变更时还是比较方便的,不用再一个个打快照了
可以结合Azure Automation来一起使用,会更简单高效
具体脚本的内容如下
# take snapshots for all vms in the resource group
# https://learn.microsoft.com/en-us/azure/virtual-machines/snapshot-copy-managed-disk?tabs=powershell
param(
[string]$VM_Resource_Group_Name,
[string]$Target_Resource_Group_Name
)
function Take-Snapshot {
param (
$Snapshot_Config,
$Snapshot_Name,
$ResourceGroupName
)
try {
$Error.clear()
Write-Output "Creating snapshot $Snapshot_Name ... "
New-AzSnapshot -Snapshot $Snapshot_Config -SnapshotName $Snapshot_Name -ResourceGroupName $ResourceGroupName -ErrorAction Stop | out-null
}
catch {
Write-Output $Error[0].exception.message
}
}
$AzureContext = (Connect-AzAccount -Identity -Environment AzureChinaCloud).context
# set and store context
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext
Select-AzSubscription -SubscriptionId "xxxxxxx";
$VMs = Get-AzVM -ResourceGroupName $VM_Resource_Group_Name -ErrorAction Stop
foreach ($vm in $VMs) {
# OS Disk
$OSDisk = $vm.StorageProfile.OsDisk
$OSDisk_ID = $vm.StorageProfile.OsDisk.ManagedDisk.id
$Snapshot_Config_OS = New-AzSnapshotConfig -SourceUri $OSDisk_ID -CreateOption Copy -Location $VM.Location -AccountType Standard_LRS
$Snapshot_Name_OS = $OSDisk.Name + "_snapshot_" + (Get-Date -Format "yyyy-MM-dd-HH-mm-ss")
$Target_Resource_Group = Get-AzResourceGroup -Name $Target_Resource_Group_Name -ErrorAction SilentlyContinue
if ($null -eq $Target_Resource_Group) {
New-AzResourceGroup -Name $Target_Resource_Group_Name -Location $VM.Location | out-null
}
Take-Snapshot -Snapshot_Config $Snapshot_Config_OS -Snapshot_Name $Snapshot_Name_OS -ResourceGroupName $Target_Resource_Group_Name
# Data disk
$Data_Disks = $vm.StorageProfile.DataDisks
if ($Data_Disks.count -ne 0) {
foreach ($Data_Disk in $Data_Disks) {
$Data_Disk_ID = $Data_Disk.ManagedDisk.id
$Snapshot_Config_Data_Disk = New-AzSnapshotConfig -SourceUri $Data_Disk_ID -CreateOption Copy -Location $VM.Location -AccountType Standard_LRS
$Snapshot_Name_Data_Disk = $Data_Disk.Name + "_snapshot_" + (Get-Date -Format "yyyy-MM-dd-HH-mm-ss")
Take-Snapshot -Snapshot_Config $Snapshot_Config_Data_Disk -Snapshot_Name $Snapshot_Name_Data_Disk -ResourceGroupName $Target_Resource_Group_Name
}
}
else {
Write-Output "No data disk found for VM $($VM.Name)"
}
}
使用时也很简单,以Azure Automation为例,创建好runbook之后,直接start,然后输入两个参数
- VM_RESOURCE_GROUP_NAME:要打快照的VM所在的resource group
- TARGET_RESOURCE_GROUP_NAME:将快照创建在哪个resource group
可以看到脚本正在运行中,会输出一些log
等待一段时间之后就能看到快照出来了