搭配使用模組登錄與 Terraform 以建立 VM 叢集Create a VM cluster with Terraform using the Module Registry

本文逐步引導您使用 Terraform Azure 計算模組建立小 VM 叢集。This article walks you through creating a small VM cluster with the Terraform Azure compute module. 在本教學課程中,您將了解如何:In this tutorial you learn how to:

  • 使用 Azure 設定驗證Set up authentication with Azure
  • 建立 Terraform 範本Create the Terraform template
  • 視覺化計劃變更Visualize the changes with plan
  • 套用設定以建立 VM 叢集Apply the configuration to create the VM cluster

如需 Terraform 的詳細資訊,請參閱 Terraform 文件For more information on Terraform, see the Terraform documentation.

使用 Azure 設定驗證Set up authentication with Azure

提示

如果您使用 Terraform 環境變數或在 Azure Cloud Shell 中執行本教學課程,請略過此步驟。If you use Terraform environment variables or run this tutorial in the Azure Cloud Shell, skip this step.

檢閱安裝 Terraform 並設定對 Azure 的存取權限,來建立 Azure 服務主體。Review Install Terraform and configure access to Azure to create an Azure service principal. 使用這個服務主體與下列程式碼,將新檔案 azureProviderAndCreds.tf 植入空的目錄中:Use this service principal to populate a new file azureProviderAndCreds.tf in an empty directory with the following code:

variable subscription_id {}
variable tenant_id {}
variable client_id {}
variable client_secret {}

provider "azurerm" {
    subscription_id = "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
    tenant_id = "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
    client_id = "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
    client_secret = "xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}

建立範本Create the template

使用下列程式碼,建立名為 main.tf 的新 Terraform 範本:Create a new Terraform template named main.tf with the following code:

module mycompute {
    source = "Azure/compute/azurerm"
    resource_group_name = "myResourceGroup"
    location = "East US 2"
    admin_password = "ComplxP@assw0rd!"
    vm_os_simple = "WindowsServer"
    remote_port = "3389"
    nb_instances = 2
    public_ip_dns = ["unique_dns_name"]
    vnet_subnet_id = "${module.network.vnet_subnets[0]}"
}

module "network" {
    source = "Azure/network/azurerm"
    location = "East US 2"
    resource_group_name = "myResourceGroup"
}

output "vm_public_name" {
    value = "${module.mycompute.public_ip_dns_name}"
}

output "vm_public_ip" {
    value = "${module.mycompute.public_ip_address}"
}

output "vm_private_ips" {
    value = "${module.mycompute.network_interface_private_ip}"
}

在設定目錄中執行terraform initRun terraform init in your configuration directory. 使用至少 0.10.6 版的 Terraform 來顯示下列輸出:Using a Terraform version of at least 0.10.6 shows the following output:

Terraform 初始化

使用 plan 視覺化變更Visualize the changes with plan

執行 terraform plan,預覽範本所建立的虛擬機器基礎結構。Run terraform plan to preview the virtual machine infrastructure created by the template.

Terraform Plan

使用套用建立虛擬機器Create the virtual machines with apply

在 Azure 上執行 terraform apply 以佈建 VM。Run terraform apply to provision the VMs on Azure.

Terraform Apply

後續步驟Next steps