使用 Terraform 來建立 Azure 虛擬機器擴展集Use Terraform to create an Azure virtual machine scale set

Azure 虛擬機器擴展集可讓您建立和管理一組完全相同、經過負載平衡的虛擬機器,其中的虛擬機器執行個體數目可以自動增加,或回應要求或定義的排程而減少。Azure virtual machine scale sets allow you to create and manage a group of identical, load balanced virtual machines where the number of virtual machine instances can automatically increase, or decrease in response to demand or a defined schedule.

在本教學課程中,您會了解如何使用 Azure Cloud Shell 來執行下列工作:In this tutorial, you learn how to use Azure Cloud Shell to perform the following tasks:

  • 設定 Terraform 部署Set up a Terraform deployment
  • 針對 Terraform 部署使用變數和輸出Use variables and outputs for Terraform deployment
  • 建立和部署網路基礎結構Create and deploy network infrastructure
  • 建立和部署虛擬機器擴展集,並將它連接到網路Create and deploy a virtual machine scale set and attach it to the network
  • 建立和部署 Jumpbox 以透過 SSH 連線到 VMCreate and deploy a jumpbox to connect to the VMs via SSH

注意

本文中使用的最新版本 Terraform 組態檔位於 GitHub 上很棒的 Terraform 存放庫中。The most recent version of the Terraform configuration files used in this article are in the Awesome Terraform repository on GitHub.

必要條件Prerequisites

建立目錄結構Create the directory structure

  1. 瀏覽至 Azure 入口網站Browse to the Azure portal.

  2. 開啟 Azure Cloud ShellOpen Azure Cloud Shell. 如果您先前未選取環境,請選取 Bash 作為您的環境。If you didn't select an environment previously, select Bash as your environment.

    Cloud Shell 提示

  3. 切換至 clouddrive 目錄。Change directories to the clouddrive directory.

    cd clouddrive
    
  4. 建立名為 vmss 的目錄。Create a directory named vmss.

    mkdir vmss
    
  5. 將目錄變更為新的目錄:Change directories to the new directory:

    cd vmss
    

建立變數定義檔Create the variables definitions file

在本節中,您要定義可自訂 Terraform 所建立資源的變數。In this section, you define the variables that customize the resources created by Terraform.

在 Azure Cloud Shell 內,執行下列步驟:Within the Azure Cloud Shell, perform the following steps:

  1. 建立名為 variables.tf 的檔案。Create a file named variables.tf.

    vi variables.tf
    
  2. 選取 I 鍵輸入插入模式。Enter insert mode by selecting the I key.

  3. 將下列程式碼貼到編輯器中:Paste the following code into the editor:

    variable "location" {
     description = "The location where resources will be created"
    }
    
    variable "tags" {
     description = "A map of the tags to use for the resources that are deployed"
     type        = "map"
    
     default = {
       environment = "codelab"
     }
    }
    
    variable "resource_group_name" {
     description = "The name of the resource group in which the resources will be created"
     default     = "myResourceGroup"
    }
    
  4. 選取 Esc 鍵結束插入模式。Exit insert mode by selecting the Esc key.

  5. 輸入下列命令來儲存檔案及結束 vi 編輯器:Save the file and exit the vi editor by entering the following command:

    :wq
    

建立輸出定義檔Create the output definitions file

在本節中,您要建立可描述部署後輸出的檔案。In this section, you create the file that describes the output after deployment.

在 Azure Cloud Shell 內,執行下列步驟:Within the Azure Cloud Shell, perform the following steps:

  1. 建立名為 output.tf 的檔案。Create a file named output.tf.

    vi output.tf
    
  2. 選取 I 鍵輸入插入模式。Enter insert mode by selecting the I key.

  3. 請將下列程式碼貼到編輯器,以公開虛擬機器的完整網域名稱 (FQDN)。Paste the following code into the editor to expose the fully qualified domain name (FQDN) for the virtual machines. :

     output "vmss_public_ip" {
         value = "${azurerm_public_ip.vmss.fqdn}"
     }
    
  4. 選取 Esc 鍵結束插入模式。Exit insert mode by selecting the Esc key.

  5. 輸入下列命令來儲存檔案及結束 vi 編輯器:Save the file and exit the vi editor by entering the following command:

    :wq
    

在範本中定義網路基礎結構Define the network infrastructure in a template

在本節中,您要在新的 Azure 資源群組中建立下列網路基礎結構:In this section, you create the following network infrastructure in a new Azure resource group:

  • 一個具有 10.0.0.0/16 位址空間的虛擬網路 (VNET)One virtual network (VNET) with the address space of 10.0.0.0/16
  • 一個具有 10.0.2.0/24 位址空間的子網路One subnet with the address space of 10.0.2.0/24
  • 兩個公用 IP 位址。Two public IP addresses. 其中一個是用於虛擬機器擴展集負載平衡器,另一個用於連線到 SSH Jubmox。One used by the virtual machine scale set load balancer, the other used to connect to the SSH jumpbox.

在 Azure Cloud Shell 內,執行下列步驟:Within the Azure Cloud Shell, perform the following steps:

  1. 建立名為 vmss.tf 的檔案來描述虛擬機器擴展集基礎結構。Create a file named vmss.tf to describe the virtual machine scale set infrastructure.

    vi vmss.tf
    
  2. 選取 I 鍵輸入插入模式。Enter insert mode by selecting the I key.

  3. 請將下列程式碼貼到檔案的結尾,以公開虛擬機器的完整網域名稱 (FQDN)。Paste the following code to the end of the file to expose the fully qualified domain name (FQDN) for the virtual machines.

    resource "azurerm_resource_group" "vmss" {
     name     = "${var.resource_group_name}"
     location = "${var.location}"
     tags     = "${var.tags}"
    }
    
    resource "random_string" "fqdn" {
     length  = 6
     special = false
     upper   = false
     number  = false
    }
    
    resource "azurerm_virtual_network" "vmss" {
     name                = "vmss-vnet"
     address_space       = ["10.0.0.0/16"]
     location            = "${var.location}"
     resource_group_name = "${azurerm_resource_group.vmss.name}"
     tags                = "${var.tags}"
    }
    
    resource "azurerm_subnet" "vmss" {
     name                 = "vmss-subnet"
     resource_group_name  = "${azurerm_resource_group.vmss.name}"
     virtual_network_name = "${azurerm_virtual_network.vmss.name}"
     address_prefix       = "10.0.2.0/24"
    }
    
    resource "azurerm_public_ip" "vmss" {
     name                         = "vmss-public-ip"
     location                     = "${var.location}"
     resource_group_name          = "${azurerm_resource_group.vmss.name}"
     allocation_method = "Static"
     domain_name_label            = "${random_string.fqdn.result}"
     tags                         = "${var.tags}"
    }
    
  4. 選取 Esc 鍵結束插入模式。Exit insert mode by selecting the Esc key.

  5. 輸入下列命令來儲存檔案及結束 vi 編輯器:Save the file and exit the vi editor by entering the following command:

    :wq
    

佈建網路基礎結構Provision the network infrastructure

在您建立組態檔 (.tf) 的目錄中,使用 Azure Cloud Shell 執行下列步驟:Using the Azure Cloud Shell from the directory where you created the configuration files (.tf) perform the following steps:

  1. 初始化 Terraform。Initialize Terraform.

    terraform init
    
  2. 執行下列命令,以在 Azure 中部署定義的基礎結構。Run the following command to deploy the defined infrastructure in Azure.

    terraform apply
    

    Terraform 會提示您輸入「位置」值,因為 location 變數會在 variables.tf 中定義,但一律不會設定。Terraform prompts you for a "location" value as the location variable is defined in variables.tf, but it's never set. 您可以輸入任何有效的位置 - 例如「美國西部」,接著選取 [輸入]。You can enter any valid location - such as "West US" followed by selecting Enter. (使用括號括住任何包含空格的值。)(Use parentheses around any value with spaces.)

  3. Terraform 會列印 output.tf 檔案中所定義的輸出。Terraform prints the output as defined in the output.tf file. 如下列螢幕擷取畫面所示,FQDN 會採用 <id>.<location>.cloudapp.azure.com 的格式。As shown in the following screenshot, the FQDN takes the form <id>.<location>.cloudapp.azure.com. ID 值是經計算的值,而位置則是您在執行 Terraform 時所提供的值。The id value is a computed value and location is the value you provide when running Terraform.

    公用 IP 位址的虛擬機器擴展集完整網域名稱

  4. 在 Azure 入口網站功能表的主功能表中,選取 [資源群組]。In the Azure portal menu, select Resource groups from the main menu.

  5. 在 [資源群組] 索引標籤上,選取 myResourceGroup 以檢視 Terraform 所建立的資源。On the Resource groups tab, select myResourceGroup to view the resources that were created by Terraform. 虛擬機器擴展集網路資源Virtual machine scale set network resources

新增虛擬機器擴展集Add a virtual machine scale set

在本節中,您會了解如何將下列資源新增到範本:In this section, you learn how to add the following resources to the template:

  • Azure 負載平衡器,以及用以提供務應用程式,並將負載平衡器連結到本文中稍早所設定公用 IP 位址的規則An Azure load balancer and rules to serve the application and attach it to the public IP address configured earlier in this article
  • Azure 後端位址集區,並將其指派給負載平衡器An Azure backend address pool and assign it to the load balancer
  • 應用程式所使用且在負載平衡器上設定的健康情況探查連接埠A health probe port used by the application and configured on the load balancer
  • 位在負載平衡器幕後的虛擬機器擴展集,在本文中稍早部署的 VNET 上執行A virtual machine scale set sitting behind the load balancer that runs on the VNET deployed earlier in this article
  • 在使用 cloud-init 的虛擬機器擴展集節點上的 NginxNginx on the nodes of the virtual machine scale using cloud-init.

在 Cloud Shell 中,執行下列步驟:In Cloud Shell, perform the following steps:

  1. 開啟 vmss.tf 組態檔。Open the vmss.tf configuration file.

    vi vmss.tf
    
  2. 請移至檔案的結尾,並選取 A 鍵來進入附加模式。Go to the end of the file and enter append mode by selecting the A key.

  3. 將下列程式碼貼到檔案的結尾:Paste the following code to the end of the file:

    resource "azurerm_lb" "vmss" {
     name                = "vmss-lb"
     location            = "${var.location}"
     resource_group_name = "${azurerm_resource_group.vmss.name}"
    
     frontend_ip_configuration {
       name                 = "PublicIPAddress"
       public_ip_address_id = "${azurerm_public_ip.vmss.id}"
     }
    
     tags = "${var.tags}"
    }
    
    resource "azurerm_lb_backend_address_pool" "bpepool" {
     resource_group_name = "${azurerm_resource_group.vmss.name}"
     loadbalancer_id     = "${azurerm_lb.vmss.id}"
     name                = "BackEndAddressPool"
    }
    
    resource "azurerm_lb_probe" "vmss" {
     resource_group_name = "${azurerm_resource_group.vmss.name}"
     loadbalancer_id     = "${azurerm_lb.vmss.id}"
     name                = "ssh-running-probe"
     port                = "${var.application_port}"
    }
    
    resource "azurerm_lb_rule" "lbnatrule" {
       resource_group_name            = "${azurerm_resource_group.vmss.name}"
       loadbalancer_id                = "${azurerm_lb.vmss.id}"
       name                           = "http"
       protocol                       = "Tcp"
       frontend_port                  = "${var.application_port}"
       backend_port                   = "${var.application_port}"
       backend_address_pool_id        = "${azurerm_lb_backend_address_pool.bpepool.id}"
       frontend_ip_configuration_name = "PublicIPAddress"
       probe_id                       = "${azurerm_lb_probe.vmss.id}"
    }
    
    resource "azurerm_virtual_machine_scale_set" "vmss" {
     name                = "vmscaleset"
     location            = "${var.location}"
     resource_group_name = "${azurerm_resource_group.vmss.name}"
     upgrade_policy_mode = "Manual"
    
     sku {
       name     = "Standard_DS1_v2"
       tier     = "Standard"
       capacity = 2
     }
    
     storage_profile_image_reference {
       publisher = "Canonical"
       offer     = "UbuntuServer"
       sku       = "16.04-LTS"
       version   = "latest"
     }
    
     storage_profile_os_disk {
       name              = ""
       caching           = "ReadWrite"
       create_option     = "FromImage"
       managed_disk_type = "Standard_LRS"
     }
    
     storage_profile_data_disk {
       lun          = 0
       caching        = "ReadWrite"
       create_option  = "Empty"
       disk_size_gb   = 10
     }
    
     os_profile {
       computer_name_prefix = "vmlab"
       admin_username       = "${var.admin_user}"
       admin_password       = "${var.admin_password}"
       custom_data          = "${file("web.conf")}"
     }
    
     os_profile_linux_config {
       disable_password_authentication = false
     }
    
     network_profile {
       name    = "terraformnetworkprofile"
       primary = true
    
       ip_configuration {
         name                                   = "IPConfiguration"
         subnet_id                              = "${azurerm_subnet.vmss.id}"
         load_balancer_backend_address_pool_ids = ["${azurerm_lb_backend_address_pool.bpepool.id}"]
         primary = true
       }
     }
    
     tags = "${var.tags}"
    }
    
  4. 選取 Esc 鍵結束插入模式。Exit insert mode by selecting the Esc key.

  5. 輸入下列命令來儲存檔案及結束 vi 編輯器:Save the file and exit the vi editor by entering the following command:

    :wq
    
  6. 建立名為 web.conf 的檔案,作為擴展集所屬虛擬機器的 cloud-init 組態。Create a file named web.conf to serve as the cloud-init configuration for the virtual machines that are part of the scale set.

    vi web.conf
    
  7. 選取 I 鍵輸入插入模式。Enter insert mode by selecting the I key.

  8. 將下列程式碼貼到編輯器中:Paste the following code into the editor:

    #cloud-config
    packages:
     - nginx
    
  9. 選取 Esc 鍵結束插入模式。Exit insert mode by selecting the Esc key.

  10. 輸入下列命令來儲存檔案及結束 vi 編輯器:Save the file and exit the vi editor by entering the following command:

    :wq
    
  11. 開啟 variables.tf 組態檔。Open the variables.tf configuration file.

    vi variables.tf
    
  12. 請移至檔案的結尾,並選取 A 鍵來進入附加模式。Go to the end of the file and enter append mode by selecting the A key.

  13. 將下列程式碼貼到檔案的結尾來自訂部署:Customize the deployment by pasting the following code to the end of the file:

    variable "application_port" {
       description = "The port that you want to expose to the external load balancer"
       default     = 80
    }
    
    variable "admin_user" {
       description = "User name to use as the admin account on the VMs that will be part of the VM Scale Set"
       default     = "azureuser"
    }
    
    variable "admin_password" {
       description = "Default password for admin account"
    }
    
  14. 選取 Esc 鍵結束插入模式。Exit insert mode by selecting the Esc key.

  15. 輸入下列命令來儲存檔案及結束 vi 編輯器:Save the file and exit the vi editor by entering the following command:

    :wq
    
  16. 建立 Terraform 計劃以視覺化虛擬機器擴展集部署。Create a Terraform plan to visualize the virtual machine scale set deployment. (您需要指定您選擇的密碼及資源的位置)。(You need to specify a password of your choosing, as well as the location for your resources.)

    terraform plan
    

    此命令的輸出應類似下列螢幕擷取畫面:The output of the command should be similar to the following screenshot:

    建立虛擬機器擴展集的輸出

  17. 在 Azure 中部署新的資源。Deploy the new resources in Azure.

    terraform apply
    

    此命令的輸出應類似下列螢幕擷取畫面:The output of the command should be similar to the following screenshot:

    Terraform 虛擬機器擴展集資源群組

  18. 開啟瀏覽器並連線到命令傳回的 FQDN。Open a browser and connect to the FQDN that was returned by the command.

    瀏覽至 FQDN 的結果

新增 SSH JumpboxAdd an SSH jumpbox

SSH jumpbox 是您在存取網路上其他伺服器時所「跳躍」通過的單一伺服器。An SSH jumpbox is a single server that you "jump" through in order to access other servers on the network. 在此步驟中,您要設定下列資源:In this step, you configure the following resources:

  • 連線到與虛擬機器擴展集相同子網路的網路介面 (或 jumpbox)。A network interface (or jumpbox) connected to the same subnet as the virtual machine scale set.

  • 使用此網路介面連線的虛擬機器。A virtual machine connected with this network interface. 此 'jumpbox' 可從遠端存取。This 'jumpbox' is remotely accessible. 一旦連線之後,您就可以透過 SSH 連線到擴展集中的任何虛擬機器。Once connected, you can SSH to any of the virtual machines in the scale set.

  1. 開啟 vmss.tf 組態檔。Open the vmss.tf configuration file.

    vi vmss.tf
    
  2. 請移至檔案的結尾,並選取 A 鍵來進入附加模式。Go to the end of the file and enter append mode by selecting the A key.

  3. 將下列程式碼貼到檔案的結尾:Paste the following code to the end of the file:

    resource "azurerm_public_ip" "jumpbox" {
     name                         = "jumpbox-public-ip"
     location                     = "${var.location}"
     resource_group_name          = "${azurerm_resource_group.vmss.name}"
     allocation_method = "Static"
     domain_name_label            = "${random_string.fqdn.result}-ssh"
     tags                         = "${var.tags}"
    }
    
    resource "azurerm_network_interface" "jumpbox" {
     name                = "jumpbox-nic"
     location            = "${var.location}"
     resource_group_name = "${azurerm_resource_group.vmss.name}"
    
     ip_configuration {
       name                          = "IPConfiguration"
       subnet_id                     = "${azurerm_subnet.vmss.id}"
       private_ip_address_allocation = "dynamic"
       public_ip_address_id          = "${azurerm_public_ip.jumpbox.id}"
     }
    
     tags = "${var.tags}"
    }
    
    resource "azurerm_virtual_machine" "jumpbox" {
     name                  = "jumpbox"
     location              = "${var.location}"
     resource_group_name   = "${azurerm_resource_group.vmss.name}"
     network_interface_ids = ["${azurerm_network_interface.jumpbox.id}"]
     vm_size               = "Standard_DS1_v2"
    
     storage_image_reference {
       publisher = "Canonical"
       offer     = "UbuntuServer"
       sku       = "16.04-LTS"
       version   = "latest"
     }
    
     storage_os_disk {
       name              = "jumpbox-osdisk"
       caching           = "ReadWrite"
       create_option     = "FromImage"
       managed_disk_type = "Standard_LRS"
     }
    
     os_profile {
       computer_name  = "jumpbox"
       admin_username = "${var.admin_user}"
       admin_password = "${var.admin_password}"
     }
    
     os_profile_linux_config {
       disable_password_authentication = false
     }
    
     tags = "${var.tags}"
    }
    
  4. 開啟 output.tf 組態檔。Open the output.tf configuration file.

    vi output.tf
    
  5. 請移至檔案的結尾,並選取 A 鍵來進入附加模式。Go to the end of the file and enter append mode by selecting the A key.

  6. 將下列程式碼貼到檔案的結尾,以在部署完成時顯示 Jumpbox 的主機名稱:Paste the following code to the end of the file to display the hostname of the jumpbox when the deployment is complete:

    output "jumpbox_public_ip" {
       value = "${azurerm_public_ip.jumpbox.fqdn}"
    }
    
  7. 選取 Esc 鍵結束插入模式。Exit insert mode by selecting the Esc key.

  8. 輸入下列命令來儲存檔案及結束 vi 編輯器:Save the file and exit the vi editor by entering the following command:

    :wq
    
  9. 部署 Jumpbox。Deploy the jumpbox.

    terraform apply
    

部署完成之後,資源群組的內容會類似於下列螢幕擷取畫面所示:Once the deployment has completed, the content of the resource group resembles that shown in the following screenshot:

Terraform 虛擬機器擴展集資源群組

注意

在 Jumpbox 和您部署的虛擬機器擴展集上,已停用以密碼登入的功能。The ability to log in with a password is disabled on the jumpbox and the virtual machine scale set that you deployed. 請使用 SSH 登入來存取虛擬機器。Log in with SSH to access the virtual machine(s).

環境清除Environment cleanup

若要刪除本教學課程中所建立的 Terraform 資源,請將下列命令輸入 Cloud Shell 中:To delete the Terraform resources that were created in this tutorial, enter the following command into Cloud Shell:

terraform destroy

解構程序可能需要幾分鐘的時間才能完成。The destruction process can take several minutes to complete.

後續步驟Next steps

在本文中,您會了解如何使用 Terraform 來建立 Azure 虛擬機器擴展集。In this article, you learned how to use Terraform to create an Azure virtual machine scale set. 以下有一些額外的資源,可協助您深入了解 Azure 上的 Terraform:Here are some additional resources to help you learn more about Terraform on Azure:

Microsoft.com 中的 Terraform 中樞 Terraform Azure 提供者文件 Terraform Azure 提供者來源 Terraform Azure 模組Terraform Hub in Microsoft.com Terraform Azure provider documentation Terraform Azure provider source Terraform Azure modules