你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

使用 Azure CLI 将托管磁盘导出/复制到存储帐户

此脚本将托管磁盘的基础 VHD 导出到相同或不同区域中的存储帐户。 它首先生成托管磁盘的 SAS URI,然后使用该 SAS URI 将 VHD 复制到存储帐户。 使用此脚本将托管磁盘复制到另一区域以进行区域扩展。 若要在 Azure 市场中发布托管磁盘的 VHD 文件,可以使用此脚本将 VHD 文件复制到存储帐户,然后生成已复制的 VHD 的 SAS URI,以便在市场中发布。

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

先决条件

示例脚本

启动 Azure Cloud Shell

Azure Cloud Shell 是免费的交互式 shell,可以使用它运行本文中的步骤。 它预安装有常用 Azure 工具并将其配置与帐户一起使用。

若要打开 Cloud Shell,只需要从代码块的右上角选择“试一试”。 也可以通过转到 https://shell.azure.com 在单独的浏览器标签页中启动 Cloud Shell。

当 Cloud Shell 打开时,请验证是否为环境选择了“Bash”。 后续会话将在 Bash 环境中使用 Azure CLI,选择“复制”以复制代码块,将其粘贴到 Cloud Shell 中,然后按 Enter 来运行它。

登录 Azure

Cloud Shell 会在登录时使用的初始帐户下自动进行身份验证。 使用以下脚本通过其他订阅登录,将 <Subscription ID> 替换为 Azure 订阅 ID。 如果没有 Azure 订阅,请在开始之前创建一个 Azure 免费帐户

subscription="<subscriptionId>" # add subscription here

az account set -s $subscription # ...or use 'az login'

有关详细信息,请参阅设置有效的订阅以交互方式登录

运行脚本

#Provide the subscription Id where managed disk is created
subscriptionId="<subscriptionId>"

#Provide the name of your resource group where managed disk is created
resourceGroupName=myResourceGroupName

#Provide the managed disk name 
diskName=myDiskName

#Provide Shared Access Signature (SAS) expiry duration in seconds e.g. 3600.
#Know more about SAS here: https://docs.microsoft.com/azure/storage/storage-dotnet-shared-access-signature-part-1
sasExpiryDuration=3600

#Provide storage account name where you want to copy the underlying VHD file of the managed disk. 
storageAccountName=mystorageaccountname

#Name of the storage container where the downloaded VHD will be stored
storageContainerName=mystoragecontainername

#Provide the key of the storage account where you want to copy the VHD 
storageAccountKey=mystorageaccountkey

#Provide the name of the destination VHD file to which the VHD of the managed disk will be copied.
destinationVHDFileName=myvhdfilename.vhd

az account set --subscription $subscriptionId

sas=$(az disk grant-access --resource-group $resourceGroupName --name $diskName --duration-in-seconds $sasExpiryDuration --query [accessSas] -o tsv)

az storage blob copy start --destination-blob $destinationVHDFileName --destination-container $storageContainerName --account-name $storageAccountName --account-key $storageAccountKey --source-uri $sas

清理资源

运行以下命令来删除资源组、VM 和所有相关资源。

az group delete --name myResourceGroupName

示例参考

此脚本使用以下命令生成托管磁盘的 SAS URI,然后使用该 SAS URI 将基础 VHD 复制到存储帐户。 表中的每条命令均链接到特定于命令的文档。

命令 说明
az disk grant-access 生成只读 SAS,使用该 SAS 可以将基础 VHD 文件复制到存储帐户或将其下载到本地
az storage blob copy start 将 blob 从一个存储帐户异步复制到另一个存储帐户

后续步骤

从 VHD 创建托管磁盘

从托管磁盘创建虚拟机

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

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