使用 CLI 将托管磁盘的快照复制到相同或不同的订阅

此脚本会将托管磁盘的快照复制到相同或不同的订阅。 将此脚本用于以下方案:

  1. 将高级存储 (Premium_LRS) 中的快照迁移到标准存储(Standard_LRS 或 Standard_ZRS)以降低成本。
  2. 将快照从本地冗余存储(Premium_LRS、Standard_LRS)迁移到区域冗余存储(Standard_ZRS),以从 ZRS 存储的更高可靠性中受益。
  3. 将快照移到同一区域中的不同订阅,以延长保留时间。

注意

两个订阅必须位于同一租户下

若要运行此示例,请安装最新版本的 Azure CLI。 若要开始,请运行 az login 以创建与 Azure 的连接。

适用于 Azure CLI 的示例是针对 bash shell 编写的。 若要在 Windows PowerShell 或命令提示符中运行此示例,可能需要更改脚本的元素。

如果还没有 Azure 订阅,可以在开始前创建一个免费帐户

示例脚本

# Verified per Raman Kumar as of 2/23/2022

# <FullScript>
#Provide the subscription Id of the subscription where snapshot exists
sourceSubscriptionId="<subscriptionId>"

#Provide the name of your resource group where snapshot exists
sourceResourceGroupName=mySourceResourceGroupName

#Provide the name of the snapshot
snapshotName=mySnapshotName

#Set the context to the subscription Id where snapshot exists
az account set --subscription $sourceSubscriptionId

#Get the snapshot Id 
snapshotId=$(az snapshot show --name $snapshotName --resource-group $sourceResourceGroupName --query [id] -o tsv)

#If snapshotId is blank then it means that snapshot does not exist.
echo 'source snapshot Id is: ' $snapshotId

#Provide the subscription Id of the subscription where snapshot will be copied to
#If snapshot is copied to the same subscription then you can skip this step
targetSubscriptionId=6492b1f7-f219-446b-b509-314e17e1efb0

#Name of the resource group where snapshot will be copied to
targetResourceGroupName=mytargetResourceGroupName

#Set the context to the subscription Id where snapshot will be copied to
#If snapshot is copied to the same subscription then you can skip this step
az account set --subscription $targetSubscriptionId

#Copy snapshot to different subscription using the snapshot Id
#We recommend you to store your snapshots in Standard storage to reduce cost. Please use Standard_ZRS in regions where zone redundant storage (ZRS) is available, otherwise use Standard_LRS
#Please check out the availability of ZRS here: https://docs.microsoft.com/en-us/azure/storage/common/storage-redundancy-zrs#support-coverage-and-regional-availability
az snapshot create --resource-group $targetResourceGroupName --name $snapshotName --source $snapshotId --sku Standard_LRS
# </FullScript>

脚本说明

此脚本使用以下命令,通过源快照的 ID 在目标订阅中创建快照。 表中的每条命令均链接到特定于命令的文档。

命令 说明
az snapshot show 使用快照的名称和资源组属性获取该快照的所有属性。 使用 ID 属性将快照复制到其他订阅。
az snapshot create 通过使用父快照的 ID 和名称在不同订阅中创建快照来复制快照。

后续步骤

从快照创建虚拟机

有关 Azure CLI 的详细信息,请参阅 Azure CLI 文档

可以在 Azure Linux VM 文档中找到其他虚拟机和托管磁盘 CLI 脚本示例。