使用現有受控 OS 磁碟搭配 CLI 以建立虛擬機器

此指令碼會連結現有受控磁碟作為 OS 磁碟,以建立虛擬機器。 在先前案例中使用此指令碼︰

  • 從不同訂用帳戶中的受控磁碟複製而來的現有受控 OS 磁碟建立 VM
  • 從特殊化 VHD 檔案建立的現有受控磁碟建立 VM
  • 從快照集建立的現有受控 OS 磁碟建立 VM

如果您沒有 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
subscriptionId="<subscriptionId>"

#Provide the name of your resource group
resourceGroupName=myResourceGroupName

#Provide the name of the Managed Disk
managedDiskName=myDiskName

#Provide the OS type
osType=linux

#Provide the name of the virtual machine
virtualMachineName=myVirtualMachineName123

#Set the context to the subscription Id where Managed Disk exists and where VM will be created
az account set --subscription $subscriptionId

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

#Create VM by attaching existing managed disks as OS
az vm create --name $virtualMachineName --resource-group $resourceGroupName --attach-os-disk $managedDiskId --os-type $osType

清除資源

執行下列命令來移除資源群組、VM 和所有相關資源。

az group delete --name myResourceGroupName

範例參考

此指令碼會使用下列命令來取得受控磁碟屬性、將受控磁碟連結至新的 VM,以及建立 VM。 下表中的每個項目都會連結至命令特定的文件。

Command 注意
az disk show 使用磁碟名稱和資源群組名稱取得受控磁碟屬性。 Id 屬性用來將受控磁碟連結至新的 VM
az vm create 建立使用受控 OS 磁碟的 VM

下一步

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

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