教學課程:使用 Azure CLI 來建立和管理 Linux VMTutorial: Create and Manage Linux VMs with the Azure CLI

Azure 虛擬機器提供完全可設定且彈性的計算環境。Azure virtual machines provide a fully configurable and flexible computing environment. 本教學課程涵蓋基本的「Azure 虛擬機器」部署項目,例如選取 VM 大小、選取 VM 映像、部署 VM。This tutorial covers basic Azure virtual machine deployment items such as selecting a VM size, selecting a VM image, and deploying a VM. 您會了解如何:You learn how to:

  • 建立及連線到 VMCreate and connect to a VM
  • 選取及使用 VM 映像Select and use VM images
  • 檢視及使用特定 VM 大小View and use specific VM sizes
  • 調整 VM 的大小Resize a VM
  • 檢視及了解 VM 狀態View and understand VM state

開啟 Azure Cloud ShellOpen Azure Cloud Shell

Azure Cloud Shell 是裝載於 Azure 中的互動式殼層環境,並且會透過瀏覽器來使用。Azure Cloud Shell is an interactive shell environment hosted in Azure and used through your browse. Azure Cloud Shell 可讓您使用 bashPowerShell 殼層來執行各種可與 Azure 服務搭配運作的工具。Azure Cloud Shell allows you to use either bash or PowerShell shells to run a variety of tools to work with Azure services. Azure Cloud Shell 已預先安裝一些命令,可讓您執行本文的內容,而不必在本機環境上安裝任何工具。Azure Cloud Shell comes pre-installed with the commands to allow you to run the content of this article without having to install anything on your local environment.

若要在 Azure Cloud Shell 上執行本文所包含的任何程式碼,請開啟 Cloud Shell 工作階段、使用某個程式碼區塊上的 [複製] 按鈕來複製程式碼,然後使用 Ctrl+Shift+V (在 Windows 和 Linux 上) 或 Cmd+Shift+V (在 macOS 上) 將程式碼貼到 Cloud Shell 工作階段中。To run any code contained in this article on Azure Cloud Shell, open a Cloud Shell session, use the Copy button on a code block to copy the code, and paste it into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS. 貼上的文字不會自動執行,因此請按 Enter 來執行程式碼。Pasted text is not automatically executed, so press Enter to run code.

您可以使用下列方式來啟動 Azure Cloud Shell:You can launch Azure Cloud Shell with:

選取程式碼區塊右上角的 [試試看] 。Select Try It in the upper-right corner of a code block. 這__不會__自動將文字複製到 Cloud Shell。This doesn't automatically copy text to Cloud Shell. Azure Cloud Shell 的試試看範例
在瀏覽器中開啟 shell.azure.comOpen shell.azure.com in your browser. 啟動 Azure Cloud Shell 按鈕Launch Azure Cloud Shell button
選取 Azure 入口網站右上角功能表上的 [Cloud Shell] 按鈕。Select the Cloud Shell button on the menu in the upper-right corner of the Azure portal. Azure 入口網站中的 [Cloud Shell] 按鈕

如果您選擇在本機安裝和使用 CLI,本教學課程會要求您執行 Azure CLI 2.0.30 版或更新版本。If you choose to install and use the CLI locally, this tutorial requires that you are running the Azure CLI version 2.0.30 or later. 執行 az --version 以尋找版本。Run az --version to find the version. 如果您需要安裝或升級,請參閱安裝 Azure CLIIf you need to install or upgrade, see Install Azure CLI.

建立資源群組Create resource group

使用 az group create 命令來建立資源群組。Create a resource group with the az group create command.

Azure 資源群組是在其中部署與管理 Azure 資源的邏輯容器。An Azure resource group is a logical container into which Azure resources are deployed and managed. 資源群組必須在虛擬機器之前建立。A resource group must be created before a virtual machine. 在此範例中,會在 eastus 區域中建立名為 myResourceGroupVM 的資源群組。In this example, a resource group named myResourceGroupVM is created in the eastus region.

az group create --name myResourceGroupVM --location eastus

在建立或修改 VM 時,會指定資源群組,在本教學課程的整個過程中可以看到此操作。The resource group is specified when creating or modifying a VM, which can be seen throughout this tutorial.

建立虛擬機器Create virtual machine

使用 az vm create 命令建立虛擬機器。Create a virtual machine with the az vm create command.

建立虛擬機器時,有數個可用的選項,例如作業系統映像、磁碟大小及系統管理認證。When you create a virtual machine, several options are available such as operating system image, disk sizing, and administrative credentials. 下列範例會建立名為 myVM 的 VM,而該 VM 執行 Ubuntu Server。The following example creates a VM named myVM that runs Ubuntu Server. VM 上會建立名為 azureuser 的使用者帳戶,而如果預設金鑰位置 (~/.ssh) 沒有 SSH 金鑰,則會加以產生:A user account named azureuser is created on the VM, and SSH keys are generated if they do not exist in the default key location (~/.ssh):

az vm create \
    --resource-group myResourceGroupVM \
    --name myVM \
    --image UbuntuLTS \
    --admin-username azureuser \
    --generate-ssh-keys

系統可能需要幾分鐘的時間來建立 VM。It may take a few minutes to create the VM. 建立 VM 之後,Azure CLI 就會輸出 VM 的相關資訊。Once the VM has been created, the Azure CLI outputs information about the VM. 請記下 publicIpAddress,此位址可用來存取虛擬機器。Take note of the publicIpAddress, this address can be used to access the virtual machine..

{
  "fqdns": "",
  "id": "/subscriptions/d5b9d4b7-6fc1-0000-0000-000000000000/resourceGroups/myResourceGroupVM/providers/Microsoft.Compute/virtualMachines/myVM",
  "location": "eastus",
  "macAddress": "00-0D-3A-23-9A-49",
  "powerState": "VM running",
  "privateIpAddress": "10.0.0.4",
  "publicIpAddress": "52.174.34.95",
  "resourceGroup": "myResourceGroupVM"
}

連接到 VMConnect to VM

您現在可以在 Azure Cloud Shell 中使用 SSH 連線到 VM,也可以從本機電腦與 VM 連線。You can now connect to the VM with SSH in the Azure Cloud Shell or from your local computer. 請使用先前步驟中記下的 publicIpAddress 來取代範例 IP 位址。Replace the example IP address with the publicIpAddress noted in the previous step.

ssh azureuser@52.174.34.95

在登入 VM 後,您就可以安裝和設定應用程式。Once logged in to the VM, you can install and configure applications. 完成時,請像平常一樣地關閉 SSH 工作階段:When you are finished, you close the SSH session as normal:

exit

了解 VM 映像Understand VM images

Azure Marketplace 包含許多可用來建立 VM 的映像。The Azure marketplace includes many images that can be used to create VMs. 在先前的步驟中,是使用 Ubuntu 映像來建立虛擬機器。In the previous steps, a virtual machine was created using an Ubuntu image. 在此步驟中,則是使用 Azure CLI 來搜尋 Marketplace 中的 CentOS 映像,然後使用此映像來部署第二部虛擬機器。In this step, the Azure CLI is used to search the marketplace for a CentOS image, which is then used to deploy a second virtual machine.

若要查看最常用的映像清單,請使用 az vm image list 命令。To see a list of the most commonly used images, use the az vm image list command.

az vm image list --output table

此命令輸出會傳回 Azure 上最常用的 VM 映像。The command output returns the most popular VM images on Azure.

Offer          Publisher               Sku                 Urn                                                             UrnAlias             Version
-------------  ----------------------  ------------------  --------------------------------------------------------------  -------------------  ---------
WindowsServer  MicrosoftWindowsServer  2016-Datacenter     MicrosoftWindowsServer:WindowsServer:2016-Datacenter:latest     Win2016Datacenter    latest
WindowsServer  MicrosoftWindowsServer  2012-R2-Datacenter  MicrosoftWindowsServer:WindowsServer:2012-R2-Datacenter:latest  Win2012R2Datacenter  latest
WindowsServer  MicrosoftWindowsServer  2008-R2-SP1         MicrosoftWindowsServer:WindowsServer:2008-R2-SP1:latest         Win2008R2SP1         latest
WindowsServer  MicrosoftWindowsServer  2012-Datacenter     MicrosoftWindowsServer:WindowsServer:2012-Datacenter:latest     Win2012Datacenter    latest
UbuntuServer   Canonical               16.04-LTS           Canonical:UbuntuServer:16.04-LTS:latest                         UbuntuLTS            latest
CentOS         OpenLogic               7.3                 OpenLogic:CentOS:7.3:latest                                     CentOS               latest
openSUSE-Leap  SUSE                    42.2                SUSE:openSUSE-Leap:42.2:latest                                  openSUSE-Leap        latest
RHEL           RedHat                  7.3                 RedHat:RHEL:7.3:latest                                          RHEL                 latest
SLES           SUSE                    12-SP2              SUSE:SLES:12-SP2:latest                                         SLES                 latest
Debian         credativ                8                   credativ:Debian:8:latest                                        Debian               latest
CoreOS         CoreOS                  Stable              CoreOS:CoreOS:Stable:latest                                     CoreOS               latest

新增 --all 引數即可查看完整的清單。A full list can be seen by adding the --all argument. 您也可以依 --publisher–-offer 來篩選此映像清單。The image list can also be filtered by --publisher or –-offer. 在此範例中,是以符合 CentOS 的供應項目作為條件來篩選此清單的所有映像。In this example, the list is filtered for all images with an offer that matches CentOS.

az vm image list --offer CentOS --all --output table

部分輸出:Partial output:

Offer             Publisher         Sku   Urn                                     Version
----------------  ----------------  ----  --------------------------------------  -----------
CentOS            OpenLogic         6.5   OpenLogic:CentOS:6.5:6.5.201501         6.5.201501
CentOS            OpenLogic         6.5   OpenLogic:CentOS:6.5:6.5.201503         6.5.201503
CentOS            OpenLogic         6.5   OpenLogic:CentOS:6.5:6.5.201506         6.5.201506
CentOS            OpenLogic         6.5   OpenLogic:CentOS:6.5:6.5.20150904       6.5.20150904
CentOS            OpenLogic         6.5   OpenLogic:CentOS:6.5:6.5.20160309       6.5.20160309
CentOS            OpenLogic         6.5   OpenLogic:CentOS:6.5:6.5.20170207       6.5.20170207

若要使用特定映像部署 VM,請記下 Urn 資料行中的值,其中包含可用來識別映像的發行者、供應項目、SKU 和版本號碼 (選擇性)。To deploy a VM using a specific image, take note of the value in the Urn column, which consists of the publisher, offer, SKU, and optionally a version number to identify the image. 指定映像時,可以使用 “latest” 來取代映像版本號碼,這會選取最新的散發版本。When specifying the image, the image version number can be replaced with “latest”, which selects the latest version of the distribution. 在此範例中,是使用 --image 引數來指定最新版的 CentOS 6.5 映像。In this example, the --image argument is used to specify the latest version of a CentOS 6.5 image.

az vm create --resource-group myResourceGroupVM --name myVM2 --image OpenLogic:CentOS:6.5:latest --generate-ssh-keys

了解 VM 大小Understand VM sizes

虛擬機器大小會決定可供虛擬機器使用的計算資源 (例如 CPU、GPU 和記憶體) 數量。A virtual machine size determines the amount of compute resources such as CPU, GPU, and memory that are made available to the virtual machine. 您必須針對預期的工作負載,來適當設定虛擬機器的大小。Virtual machines need to be sized appropriately for the expected work load. 如果工作負載增加,可以調整現有虛擬機器的大小。If workload increases, an existing virtual machine can be resized.

VM 大小VM Sizes

下表會將大小分類成各種使用案例。The following table categorizes sizes into use cases.

類型Type 大小Sizes 說明Description
一般用途General purpose Dsv3、Dv3、DSv2、Dv2、DS、D、Av2、A0-7Dsv3, Dv3, DSv2, Dv2, DS, D, Av2, A0-7 平衡的 CPU 對記憶體。Balanced CPU-to-memory. 適用於開發/測試及小型到中型應用程式和資料解決方案。Ideal for dev / test and small to medium applications and data solutions.
計算最佳化Compute optimized Fs、FFs, F CPU 與記憶體的比例高。High CPU-to-memory. 適用於中流量應用程式、網路設備,以及批次處理。Good for medium traffic applications, network appliances, and batch processes.
記憶體最佳化Memory optimized Esv3、Ev3、M、GS、G、DSv2、DS、Dv2、DEsv3, Ev3, M, GS, G, DSv2, DS, Dv2, D 記憶體與核心的比例高。High memory-to-core. 適用於關聯式資料庫、中型到大型快取,以及記憶體內分析。Great for relational databases, medium to large caches, and in-memory analytics.
儲存體最佳化Storage optimized LsLs 高磁碟輸送量及 IO。High disk throughput and IO. 適用於巨量資料、SQL 及 NoSQL 資料庫。Ideal for Big Data, SQL, and NoSQL databases.
GPUGPU NV、NCNV, NC 以大量圖形轉譯和視訊編輯為目標的特製化 VM。Specialized VMs targeted for heavy graphic rendering and video editing.
高效能High performance H、A8-11H, A8-11 我們的最強大 CPU VM,可搭配選用的高輸送量網路介面 (RDMA)。Our most powerful CPU VMs with optional high-throughput network interfaces (RDMA).

尋找可用的 VM 大小Find available VM sizes

若要查看特定區域中可用的 VM 大小清單,請使用 az vm list-sizes 命令。To see a list of VM sizes available in a particular region, use the az vm list-sizes command.

az vm list-sizes --location eastus --output table

部分輸出:Partial output:

  MaxDataDiskCount    MemoryInMb  Name                      NumberOfCores    OsDiskSizeInMb    ResourceDiskSizeInMb
------------------  ------------  ----------------------  ---------------  ----------------  ----------------------
                 2          3584  Standard_DS1                          1           1047552                    7168
                 4          7168  Standard_DS2                          2           1047552                   14336
                 8         14336  Standard_DS3                          4           1047552                   28672
                16         28672  Standard_DS4                          8           1047552                   57344
                 4         14336  Standard_DS11                         2           1047552                   28672
                 8         28672  Standard_DS12                         4           1047552                   57344
                16         57344  Standard_DS13                         8           1047552                  114688
                32        114688  Standard_DS14                        16           1047552                  229376
                 1           768  Standard_A0                           1           1047552                   20480
                 2          1792  Standard_A1                           1           1047552                   71680
                 4          3584  Standard_A2                           2           1047552                  138240
                 8          7168  Standard_A3                           4           1047552                  291840
                 4         14336  Standard_A5                           2           1047552                  138240
                16         14336  Standard_A4                           8           1047552                  619520
                 8         28672  Standard_A6                           4           1047552                  291840
                16         57344  Standard_A7                           8           1047552                  619520

建立特定大小的 VMCreate VM with specific size

在先前的 VM 建立範例中,並未提供大小,因此是採用預設大小。In the previous VM creation example, a size was not provided, which results in a default size. 您可以在建立 VM 時,使用 az vm create--size 引數來選取 VM 大小。A VM size can be selected at creation time using az vm create and the --size argument.

az vm create \
    --resource-group myResourceGroupVM \
    --name myVM3 \
    --image UbuntuLTS \
    --size Standard_F4s \
    --generate-ssh-keys

調整 VM 的大小Resize a VM

在部署 VM 之後,可以調整其大小以增加或減少資源配置。After a VM has been deployed, it can be resized to increase or decrease resource allocation. 您可以使用 az vm show 檢視 VM 目前的大小:You can view the current of size of a VM with az vm show:

az vm show --resource-group myResourceGroupVM --name myVM --query hardwareProfile.vmSize

在調整 VM 大小之前,請先檢查目前的 Azure 叢集上是否有所需的大小可用。Before resizing a VM, check if the desired size is available on the current Azure cluster. az vm list-vm-resize-options 命令會傳回大小清單。The az vm list-vm-resize-options command returns the list of sizes.

az vm list-vm-resize-options --resource-group myResourceGroupVM --name myVM --query [].name

如果有所需的大小可用,即可從已開機狀態調整 VM 的大小,但是會在作業期間重新開機。If the desired size is available, the VM can be resized from a powered-on state, however it is rebooted during the operation. 請使用 az vm resize 命令來執行調整大小作業。Use the az vm resize command to perform the resize.

az vm resize --resource-group myResourceGroupVM --name myVM --size Standard_DS4_v2

如果目前的叢集上沒有所需的大小,則必須先將 VM 解除配置,才能進行調整大小作業。If the desired size is not on the current cluster, the VM needs to be deallocated before the resize operation can occur. 請使用 az vm deallocate 命令將 VM 停止並解除配置。Use the az vm deallocate command to stop and deallocate the VM. 請注意,重新開啟 VM 電源之後,可能會移除暫存磁碟上的任何資料。Note, when the VM is powered back on, any data on the temp disk may be removed. 公用 IP 位址也會變更,除非使用的是靜態 IP 位址。The public IP address also changes unless a static IP address is being used.

az vm deallocate --resource-group myResourceGroupVM --name myVM

一旦解除配置,便可以調整大小。Once deallocated, the resize can occur.

az vm resize --resource-group myResourceGroupVM --name myVM --size Standard_GS1

調整大小之後,即可重新啟動 VM。After the resize, the VM can be started.

az vm start --resource-group myResourceGroupVM --name myVM

VM 電源狀態VM power states

Azure VM 的電源狀態可以是許多電源狀態的其中一種。An Azure VM can have one of many power states. 這個狀態代表從 Hypervisor 的觀點來看,VM 的目前狀態。This state represents the current state of the VM from the standpoint of the hypervisor.

電源狀態Power states

電源狀態Power State 說明Description
啟動中Starting 表示虛擬機器正在啟動。Indicates the virtual machine is being started.
執行中Running 表示虛擬機器正在執行。Indicates that the virtual machine is running.
停止中Stopping 表示虛擬機器正在停止。Indicates that the virtual machine is being stopped.
已停止Stopped 表示虛擬機器已停止。Indicates that the virtual machine is stopped. 處於已停止狀態的虛擬機器仍然會產生運算費用。Virtual machines in the stopped state still incur compute charges.
正在解除配置Deallocating 表示虛擬機器正在解除配置。Indicates that the virtual machine is being deallocated.
已解除配置Deallocated 表示虛擬機器已從 Hypervisor 中移除,但仍可在控制平面中使用。Indicates that the virtual machine is removed from the hypervisor but still available in the control plane. 處於「已解除配置」狀態的虛擬機器不會產生計算費用。Virtual machines in the Deallocated state do not incur compute charges.
- 表示虛擬機器的電源狀態不明。Indicates that the power state of the virtual machine is unknown.

尋找電源狀態Find the power state

若要擷取特定 VM 的狀態,請使用 az vm get-instance-view 命令。To retrieve the state of a particular VM, use the az vm get-instance-view command. 請務必為虛擬機器和資源群組指定有效的名稱。Be sure to specify a valid name for a virtual machine and resource group.

az vm get-instance-view \
    --name myVM \
    --resource-group myResourceGroupVM \
    --query instanceView.statuses[1] --output table

輸出:Output:

ode                DisplayStatus    Level
------------------  ---------------  -------
PowerState/running  VM running       Info

管理工作Management tasks

在虛擬機器的生命週期內,您可以執行一些管理工作,例如啟動、停止或刪除虛擬機器。During the life-cycle of a virtual machine, you may want to run management tasks such as starting, stopping, or deleting a virtual machine. 此外,您可以建立指令碼來自動執行重複或複雜的工作。Additionally, you may want to create scripts to automate repetitive or complex tasks. 使用 Azure CLI,可以從命令列或在指令碼中執行許多常見的管理工作。Using the Azure CLI, many common management tasks can be run from the command line or in scripts.

取得 IP 位址Get IP address

此命令會傳回虛擬機器的私人和公用 IP 位址。This command returns the private and public IP addresses of a virtual machine.

az vm list-ip-addresses --resource-group myResourceGroupVM --name myVM --output table

停止虛擬機器Stop virtual machine

az vm stop --resource-group myResourceGroupVM --name myVM

啟動虛擬機器Start virtual machine

az vm start --resource-group myResourceGroupVM --name myVM

刪除資源群組Delete resource group

刪除資源群組會同時刪除其內含的所有資源,例如 VM、虛擬網路和磁碟。Deleting a resource group also deletes all resources contained within, such as the VM, virtual network, and disk. --no-wait 參數不會等待作業完成,就會將控制項傳回給提示字元。The --no-wait parameter returns control to the prompt without waiting for the operation to complete. --yes 參數會確認您想要刪除資源,而不另外對您提示將要進行此作業。The --yes parameter confirms that you wish to delete the resources without an additional prompt to do so.

az group delete --name myResourceGroupVM --no-wait --yes

後續步驟Next steps

在本教學課程中,您已了解基本的 VM 建立和管理,像是如何:In this tutorial, you learned about basic VM creation and management such as how to:

  • 建立及連線到 VMCreate and connect to a VM
  • 選取及使用 VM 映像Select and use VM images
  • 檢視及使用特定 VM 大小View and use specific VM sizes
  • 調整 VM 的大小Resize a VM
  • 檢視及了解 VM 狀態View and understand VM state

請前進到下一個教學課程,以了解 VM 磁碟。Advance to the next tutorial to learn about VM disks.