Share via


使用 Azure CLI 將受控磁碟匯出/複製到儲存體帳戶

此指令碼會將受控磁碟的基礎 VHD 匯出到相同或不同區域的儲存體帳戶。 它會先產生受控磁碟的 SAS URI,然後用它來將 VHD 複製到儲存體帳戶。 使用此指令碼將受控磁碟複製到其他區域以進行區域擴充。 如果想要在 Azure Marketplace 中發行受控磁碟的 VHD 檔案,可以使用此指令碼將 VHD 檔案複製到儲存體帳戶,然後產生所複製 VHD 的 SAS URI,以在 Marketplace 中發佈它。

如果您沒有 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 訂用帳戶識別碼。 如果您沒有 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 複製到儲存體帳戶。 下表中的每個命令都會連結至命令特定的文件。

Command 注意
az disk grant-access 產生唯讀 SAS,用來將基礎 VHD 檔案複製到儲存體帳戶,或將它下載到內部部署
az storage blob copy start 以非同步方式在儲存體帳戶間複製 blob

下一步

從 VHD 建立受控磁碟

從受控磁碟建立虛擬機器

如需 Azure CLI 的詳細資訊,請參閱 Azure CLI 文件

您可以在 Azure Linux VM 文件中找到其他的虛擬機器和受控磁碟 CLI 指令碼範例。