使用 CLI 從快照集建立虛擬機器

此指令碼會從 OS 磁碟的快照集建立虛擬機器。

若要執行此範例,請安裝最新版的 Azure CLI。 若要啟動,請執行 az login 來建立與 Azure 的連線。

Azure CLI 的範例專為 bash 殼層撰寫。 若要在 Windows PowerShell 或命令提示字元中執行此範例,您可能需要變更指令碼的元素。

如果您沒有 Azure 訂用帳戶,請在開始之前先建立 Azure 免費帳戶

範例指令碼

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

# <FullScript>
#Provide the subscription Id of the subscription where you want to create Managed Disks
subscriptionId="<subscriptionId>"

#Provide the name of your resource group
resourceGroupName=myResourceGroupName

#Provide the name of the snapshot that will be used to create Managed Disks
snapshotName=mySnapshotName

#Provide the name of the Managed Disk
osDiskName=myOSDiskName

#Provide the size of the disks in GB. It should be greater than the VHD file size.
diskSize=128

#Provide the storage type for Managed Disk. Premium_LRS or Standard_LRS.
storageType=Premium_LRS

#Provide the OS type
osType=linux

#Provide the name of the virtual machine
virtualMachineName=myVirtualMachineName


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

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

#Create a new Managed Disks using the snapshot Id
az disk create --resource-group $resourceGroupName --name $osDiskName --sku $storageType --size-gb $diskSize --source $snapshotId 

#Create VM by attaching created managed disks as OS
az vm create --name $virtualMachineName --resource-group $resourceGroupName --attach-os-disk $osDiskName --os-type $osType
# </FullScript>

清除部署

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

az group delete --name myResourceGroup

指令碼說明

此指令碼使用下列命令來建立受控磁碟、虛擬機器和所有相關資源。 下表中的每個命令都會連結至命令特定的文件。

Command 注意
az snapshot show 使用快照集名稱和資源群組名稱取得快照集。 傳回物件的 Id 屬性用來建立受控磁碟。
az disk create 使用快照集識別碼、磁碟名稱、儲存體類型和大小,從快照集建立受控磁碟
az vm create 建立使用受控 OS 磁碟的 VM

後續步驟

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

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