安裝和設定 Terraform 以在 Azure 中佈建 VM 和的其他基礎結構Install and configure Terraform to provision VMs and other infrastructure into Azure

Terraform 使用簡易範本化語言,提供簡單的方法來定義、預覽及部署雲端基礎結構。Terraform provides an easy way to define, preview, and deploy cloud infrastructure by using a simple templating language. 本文說明在 Azure 中使用 Terraform 來佈建資源的必要步驟。This article describes the necessary steps to use Terraform to provision resources in Azure.

若要深入了解如何搭配 Azure 使用 Terraform,請造訪 Terraform 中樞To learn more about how to use Terraform with Azure, visit the Terraform Hub.

使用 Azure Cloud ShellUse Azure Cloud Shell

Azure Cloud Shell 是裝載於 Azure 中的互動式殼層環境,可在瀏覽器中使用。Azure hosts Azure Cloud Shell, an interactive shell environment that you can use through your browser. Cloud Shell 可讓您使用 bashPowerShell 以與 Azure 服務搭配使用。Cloud Shell lets you use either bash or PowerShell to work with Azure services. Azure Cloud Shell 已預先安裝一些命令,可讓您執行本文提到的程式碼,而不必在本機環境上安裝任何工具。You can use the Cloud Shell pre-installed commands to run the code in this article without having to install anything on your local environment.

若要啟動 Azure Cloud Shell:To launch Azure Cloud Shell:

選項Option 範例/連結Example/Link
選取程式碼區塊右上角的 [試試看] 。Select Try It in the upper-right corner of a code block. 選取 [試用] 並不會自動將程式碼複製到 Cloud Shell 中。Selecting Try It doesn't automatically copy the code to Cloud Shell. Azure Cloud Shell 的試試看範例
請前往 https://shell.azure.com 或選取 [啟動 Cloud Shell] 按鈕,在瀏覽器中開啟 Cloud Shell。Go to https://shell.azure.com or select the Launch Cloud Shell button to open Cloud Shell in your browser. 在新視窗中啟動 Cloud ShellLaunch Cloud Shell in a new window
選取 Azure 入口網站右上角功能表列中的 [Cloud Shell] 按鈕。Select the Cloud Shell button on the top-right menu bar in the Azure portal. Azure 入口網站中的 [Cloud Shell] 按鈕

若要在 Azure Cloud Shell 中執行本文中的程式碼:To run the code in this article in Azure Cloud Shell:

  1. 啟動 Cloud Shell。Launch Cloud Shell.

  2. 選取程式碼區塊上的 [複製] 按鈕,複製程式碼。Select the Copy button on a code block to copy the code.

  3. 在 Windows 和 Linux 上按 Ctrl+Shift+V;或在 macOS 上按 Cmd+Shift+V,將程式碼貼到 Cloud Shell工作階段中。Paste the code into the Cloud Shell session with Ctrl+Shift+V on Windows and Linux, or Cmd+Shift+V on macOS.

  4. 按下 Enter 鍵執行程式碼。Press Enter to run the code.

Terraform 預設會安裝在 Cloud Shell 中。Terraform is installed by default in the Cloud Shell. 如果您選擇在本機安裝 Terraform,請完成下一個步驟,否則請繼續進行設定 Terraform 以存取 AzureIf you choose to install Terraform locally, complete the next step, otherwise continue to Set up Terraform access to Azure.

安裝 TerraformInstall Terraform

若要安裝 Terraform,請將適合您作業系統的套件下載到個別的安裝目錄中。To install Terraform, download the appropriate package for your operating system into a separate install directory. 此下載包含單一可執行檔,您也應該為其定義全域路徑。The download contains a single executable file, for which you should also define a global path. 如需如何在 Linux 和 Mac 上設定路徑的指示,請移至此網頁For instructions on how to set the path on Linux and Mac, go to this webpage. 如需如何在 Windows 上設定路徑的指示,請移至此網頁For instructions on how to set the path on Windows, go to this webpage.

使用 terraform 命令確認路徑組態。Verify your path configuration with the terraform command. 可用的 Terraform 選項清單會隨即顯示,如下列輸出範例所示:A list of available Terraform options is shown, as in the following example output:

azureuser@Azure:~$ terraform
Usage: terraform [--version] [--help] <command> [args]

設定 Terraform 對 Azure 的 存取權Set up Terraform access to Azure

若要讓 Terraform 將資源佈建至 Azure,請建立 Azure AD 服務主體To enable Terraform to provision resources into Azure, create an Azure AD service principal. 此服務主體會授與您的 Terraform 指令碼,讓您可以在 Azure 訂用帳戶中佈建資源。The service principal grants your Terraform scripts to provision resources in your Azure subscription.

如果您有多個 Azure 訂用帳戶, 請先使用az account list查詢您的帳戶, 以取得訂用帳戶識別碼和租使用者識別碼值的清單:If you have multiple Azure subscriptions, first query your account with az account list to get a list of subscription ID and tenant ID values:

az account list --query "[].{name:name, subscriptionId:id, tenantId:tenantId}"

若要使用選取的訂用帳戶,請使用 az account set 為此工作階段設定訂用帳戶。To use a selected subscription, set the subscription for this session with az account set. 設定 SUBSCRIPTION_ID 環境變數,以保存從您要使用之訂用帳戶傳回的 id 欄位值:Set the SUBSCRIPTION_ID environment variable to hold the value of the returned id field from the subscription you want to use:

az account set --subscription="${SUBSCRIPTION_ID}"

現在,您可以建立要與 Terraform 搭配使用的服務主體。Now you can create a service principal for use with Terraform. 使用 az ad sp create-for-rbac,並將 [範圍] 設為您的訂用帳戶,如下所示:Use az ad sp create-for-rbac, and set the scope to your subscription as follows:

az ad sp create-for-rbac --role="Contributor" --scopes="/subscriptions/${SUBSCRIPTION_ID}"

隨即傳回您的 appIdpasswordsp_nametenantYour appId, password, sp_name, and tenant are returned. 記下 appIdpasswordMake a note of the appId and password.

設定 Terraform 環境變數Configure Terraform environment variables

若要設定 Terraform 以使用您的 Azure AD 服務主體,請設定下列環境變數,然後讓 Azure Terraform 模組使用這些變數。To configure Terraform to use your Azure AD service principal, set the following environment variables, which are then used by the Azure Terraform modules. 如果使用 Azure 公用以外的 Azure 雲端,您也可以設定環境。You can also set the environment if working with an Azure cloud other than Azure public.

  • ARM_SUBSCRIPTION_ID
  • ARM_CLIENT_ID
  • ARM_CLIENT_SECRET
  • ARM_TENANT_ID
  • ARM_ENVIRONMENT

您可以使用下列範例殼層指令碼來設定這些變數:You can use the following sample shell script to set those variables:

#!/bin/sh
echo "Setting environment variables for Terraform"
export ARM_SUBSCRIPTION_ID=your_subscription_id
export ARM_CLIENT_ID=your_appId
export ARM_CLIENT_SECRET=your_password
export ARM_TENANT_ID=your_tenant_id

# Not needed for public, required for usgovernment, german, china
export ARM_ENVIRONMENT=public

執行指令碼範例Run a sample script

在空的目錄中建立檔案 test.tf,並在下列指令碼中貼上。Create a file test.tf in an empty directory and paste in the following script.

provider "azurerm" {
}
resource "azurerm_resource_group" "rg" {
        name = "testResourceGroup"
        location = "westus"
}

儲存檔案,然後初始化 Terraform 部署。Save the file and then initialize the Terraform deployment. 此步驟會下載建立 Azure 資源群組所需的 Azure 模組。This step downloads the Azure modules required to create an Azure resource group.

terraform init

輸出類似於下列範例:The output is similar to the following example:

* provider.azurerm: version = "~> 0.3"

Terraform has been successfully initialized!

您可以使用 Terraform 指令碼 terraform plan 來預覽要完成的動作。You can preview the actions to be completed by the Terraform script with terraform plan. 準備好建立資源群組時,即可套用您的 Terraform 計劃,如下所示:When ready to create the resource group, apply your Terraform plan as follows:

terraform apply

輸出類似於下列範例:The output is similar to the following example:

An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
  + create

Terraform will perform the following actions:

  + azurerm_resource_group.rg
      id:       <computed>
      location: "westus"
      name:     "testResourceGroup"
      tags.%:   <computed>

azurerm_resource_group.rg: Creating...
  location: "" => "westus"
  name:     "" => "testResourceGroup"
  tags.%:   "" => "<computed>"
azurerm_resource_group.rg: Creation complete after 1s

後續步驟Next steps

在本文中,您已安裝 Terraform 或使用 Cloud Shell 來設定 Azure 認證,以及開始在 Azure 訂用帳戶中建立資源。In this article, you installed Terraform or used the Cloud Shell to configure Azure credentials and start creating resources in your Azure subscription. 若要在 Azure 中建立更完整的 Terraform 部署,請參閱下列文章:To create a more complete Terraform deployment in Azure, see the following article: