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

此脚本会将托管磁盘复制到位于同一区域的相同或不同的订阅中。 仅当订阅属于同一 Azure AD 租户时,复制才适用。

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

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

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

示例脚本

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

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

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

#Provide the name of the managed disk
managedDiskName=myDiskName

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

#Get the managed disk Id 
managedDiskId=$(az disk show --name $managedDiskName --resource-group $sourceResourceGroupName --query [id] -o tsv)

#If managedDiskId is blank then it means that managed disk does not exist.
echo 'source managed disk Id is: ' $managedDiskId

#Provide the subscription Id of the subscription where managed disk will be copied to
targetSubscriptionId=6492b1f7-f219-446b-b509-314e17e1efb0

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

#Set the context to the subscription Id where managed disk will be copied to
az account set --subscription $targetSubscriptionId

#Copy managed disk to different subscription using managed disk Id
az disk create --resource-group $targetResourceGroupName --name $managedDiskName --source $managedDiskId
# </FullScript>

脚本说明

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

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

后续步骤

从托管磁盘创建虚拟机

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

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