快速入門:使用 Terraform 在 Azure 中建立 Linux VM 叢集

適用於:✔️ Linux VM

本文說明如何使用 Terraform 在 Azure 中建立 Linux VM 叢集(包含兩個 Linux VM 執行個體)。

在本文中,您將學會如何:

必要條件

實作 Terraform 程式碼

  1. 建立目錄,然後在目錄中測試範例 Terraform 程式碼,並將其設為目前的目錄。

  2. 建立名為 providers.tf 的檔案,並插入下列程式碼:

    terraform {
      required_version = ">=1.0"
      required_providers {
        azapi = {
          source  = "azure/azapi"
          version = "~>1.5"
        }
        azurerm = {
          source  = "hashicorp/azurerm"
          version = "~>3.0"
        }
        random = {
          source  = "hashicorp/random"
          version = "~>3.0"
        }
      }
    }
    provider "azurerm" {
      features {}
    }
    
  3. 建立名為 ssh.tf 的檔案,並插入下列程式碼:

    resource "random_pet" "ssh_key_name" {
      prefix    = "ssh"
      separator = ""
    }
    
    resource "azapi_resource_action" "ssh_public_key_gen" {
      type        = "Microsoft.Compute/sshPublicKeys@2022-11-01"
      resource_id = azapi_resource.ssh_public_key.id
      action      = "generateKeyPair"
      method      = "POST"
    
      response_export_values = ["publicKey", "privateKey"]
    }
    
    resource "azapi_resource" "ssh_public_key" {
      type      = "Microsoft.Compute/sshPublicKeys@2022-11-01"
      name      = random_pet.ssh_key_name.id
      location  = azurerm_resource_group.rg.location
      parent_id = azurerm_resource_group.rg.id
    }
    
    output "key_data" {
      value = jsondecode(azapi_resource_action.ssh_public_key_gen.output).publicKey
    }
    
  4. 建立名為 main.tf 的檔案,並插入下列程式碼:

    resource "random_pet" "rg_name" {
      prefix = var.resource_group_name_prefix
    }
    
    resource "azurerm_resource_group" "rg" {
      name     = random_pet.rg_name.id
      location = var.resource_group_location
    }
    
    resource "random_pet" "azurerm_virtual_network_name" {
      prefix = "vnet"
    }
    
    resource "azurerm_virtual_network" "test" {
      name                = random_pet.azurerm_virtual_network_name.id
      address_space       = ["10.0.0.0/16"]
      location            = azurerm_resource_group.rg.location
      resource_group_name = azurerm_resource_group.rg.name
    }
    
    resource "random_pet" "azurerm_subnet_name" {
      prefix = "sub"
    }
    
    resource "azurerm_subnet" "test" {
      name                 = random_pet.azurerm_subnet_name.id
      resource_group_name  = azurerm_resource_group.rg.name
      virtual_network_name = azurerm_virtual_network.test.name
      address_prefixes     = ["10.0.2.0/24"]
    }
    
    resource "azurerm_public_ip" "test" {
      name                = "publicIPForLB"
      location            = azurerm_resource_group.rg.location
      resource_group_name = azurerm_resource_group.rg.name
      allocation_method   = "Static"
    }
    
    resource "azurerm_lb" "test" {
      name                = "loadBalancer"
      location            = azurerm_resource_group.rg.location
      resource_group_name = azurerm_resource_group.rg.name
    
      frontend_ip_configuration {
        name                 = "publicIPAddress"
        public_ip_address_id = azurerm_public_ip.test.id
      }
    }
    
    resource "azurerm_lb_backend_address_pool" "test" {
      loadbalancer_id = azurerm_lb.test.id
      name            = "BackEndAddressPool"
    }
    
    resource "azurerm_network_interface" "test" {
      count               = 2
      name                = "acctni${count.index}"
      location            = azurerm_resource_group.rg.location
      resource_group_name = azurerm_resource_group.rg.name
    
      ip_configuration {
        name                          = "testConfiguration"
        subnet_id                     = azurerm_subnet.test.id
        private_ip_address_allocation = "Dynamic"
      }
    }
    
    resource "azurerm_availability_set" "avset" {
      name                         = "avset"
      location                     = azurerm_resource_group.rg.location
      resource_group_name          = azurerm_resource_group.rg.name
      platform_fault_domain_count  = 2
      platform_update_domain_count = 2
      managed                      = true
    }
    
    resource "random_pet" "azurerm_linux_virtual_machine_name" {
      prefix = "vm"
    }
    
    resource "azurerm_linux_virtual_machine" "test" {
      count                 = 2
      name                  = "${random_pet.azurerm_linux_virtual_machine_name.id}${count.index}"
      location              = azurerm_resource_group.rg.location
      availability_set_id   = azurerm_availability_set.avset.id
      resource_group_name   = azurerm_resource_group.rg.name
      network_interface_ids = [azurerm_network_interface.test[count.index].id]
      size                  = "Standard_DS1_v2"
    
      # Uncomment this line to delete the OS disk automatically when deleting the VM
      # delete_os_disk_on_termination = true
    
      # Uncomment this line to delete the data disks automatically when deleting the VM
      # delete_data_disks_on_termination = true
    
      source_image_reference {
        publisher = "Canonical"
        offer     = "UbuntuServer"
        sku       = "16.04-LTS"
        version   = "latest"
      }
    
      admin_ssh_key {
        username   = var.username
        public_key = jsondecode(azapi_resource_action.ssh_public_key_gen.output).publicKey
      }
    
      os_disk {
        caching              = "ReadWrite"
        storage_account_type = "Standard_LRS"
        name                 = "myosdisk${count.index}"
      }
    
      computer_name  = "hostname"
      admin_username = var.username
    }
    
    resource "azurerm_managed_disk" "test" {
      count                = 2
      name                 = "datadisk_existing_${count.index}"
      location             = azurerm_resource_group.rg.location
      resource_group_name  = azurerm_resource_group.rg.name
      storage_account_type = "Standard_LRS"
      create_option        = "Empty"
      disk_size_gb         = "1024"
    }
    
    resource "azurerm_virtual_machine_data_disk_attachment" "test" {
      count              = 2
      managed_disk_id    = azurerm_managed_disk.test[count.index].id
      virtual_machine_id = azurerm_linux_virtual_machine.test[count.index].id
      lun                = "10"
      caching            = "ReadWrite"
    }
    
  5. 建立名為 variables.tf 的檔案,並插入下列程式碼:

    variable "resource_group_location" {
      type        = string
      description = "Location for all resources."
      default     = "eastus"
    }
    
    variable "resource_group_name_prefix" {
      type        = string
      description = "Prefix of the resource group name that's combined with a random ID so name is unique in your Azure subscription."
      default     = "rg"
    }
    
    variable "username" {
      type        = string
      description = "The username for the local account that will be created on the new VM."
      default     = "azureadmin"
    }
    
  6. 建立名為 outputs.tf 的檔案,並插入下列程式碼:

    output "resource_group_name" {
      value = azurerm_resource_group.rg.name
    }
    
    output "virtual_network_name" {
      value = azurerm_virtual_network.test.name
    }
    
    output "subnet_name" {
      value = azurerm_subnet.test.name
    }
    
    output "linux_virtual_machine_names" {
      value = [for s in azurerm_linux_virtual_machine.test : s.name[*]]
    }
    

初始化 Terraform

執行 terraform init 來初始化 Terraform 部署。 此命令會下載管理 Azure 資源所需的 Azure 提供者。

terraform init -upgrade

重點︰

  • -upgrade 參數會將必要的提供者外掛程式升級至符合設定版本條件約束的最新版本。

建立 Terraform 執行計畫

執行 terraform plan 以建立執行計畫。

terraform plan -out main.tfplan

重點︰

  • terraform plan 命令會建立執行計畫,但不會執行。 相反地,其會決定要在您指定的設定檔中建立設定所需的動作。 此模式可讓您在對實際資源進行任何變更之前,先確認執行方案是否符合您的預期。
  • 選用的 -out 參數可讓您指定計畫的輸出檔。 使用 -out 參數可確保您所檢閱的方案就是所套用的方案。
  • 若要閱讀保存執行方案和安全性的詳細資訊,請參閱安全性警告一節

套用 Terraform 執行計畫

執行 terraform apply 將執行計畫套用至您的雲端基礎結構。

terraform apply main.tfplan

重點︰

  • 範例 terraform apply 命令會假設您先前已執行 terraform plan -out main.tfplan
  • 如果您為 -out 參數指定了不同的檔案名稱,請在呼叫 terraform apply 時使用該檔案名稱。
  • 若您未使用 -out 參數,請呼叫 terraform apply,不需要使用參數。

在 Terraform 的虛擬機器建立過程中,不會像 Azure 入口網站那樣顯示成本資訊。 如果您想要深入了解虛擬機器的成本運作方式,請參閱成本最佳化概觀頁面 (部分機器翻譯)。

驗證結果

  1. 取得 Azure 資源群組名稱。

    resource_group_name=$(terraform output -raw resource_group_name)
    
  2. 使用 JMESPath 查詢執行 az vm list,以顯示在資源群組中建立的虛擬機器名稱。

    az vm list \
      --resource-group $resource_group_name \
      --query "[].{\"VM Name\":name}" -o table
    

清除資源

當您不再需要透過 Terraform 建立的資源時,請執行下列步驟:

  1. 執行 terraform plan 並指定 destroy 旗標。

    terraform plan -destroy -out main.destroy.tfplan
    

    重點︰

    • terraform plan 命令會建立執行計畫,但不會執行。 相反地,其會決定要在您指定的設定檔中建立設定所需的動作。 此模式可讓您在對實際資源進行任何變更之前,先確認執行方案是否符合您的預期。
    • 選用的 -out 參數可讓您指定計畫的輸出檔。 使用 -out 參數可確保您所檢閱的方案就是所套用的方案。
    • 若要閱讀保存執行方案和安全性的詳細資訊,請參閱安全性警告一節
  2. 執行 terraform apply 以套用執行方案。

    terraform apply main.destroy.tfplan
    

對 Azure 上的 Terraform 進行疑難排解

針對在 Azure 上使用 Terraform 時的常見問題進行疑難排解

下一步