快速入門:使用 Azure Export for Terraform 導出您的第一個資源

本文說明如何使用 Azure Export for Terraform 將 Azure 資源導出至本機狀態檔案

  • 使用 Azure CLI 或 Azure PowerShell 建立測試 Azure 資源群組。
  • 使用 Azure CLI 或 Azure PowerShell 建立測試 Linux 虛擬機。
  • 將資源群組和虛擬機的狀態從 Azure 匯出至本機狀態檔案。
  • 測試本機狀態是否符合 Azure 中的資源狀態。

必要條件

建立測試 Azure 資源

建立 Linux VM。

  1. 執行 az group create 以建立 Azure 資源群組。

    az group create --name myResourceGroup --location eastus
    
  2. 執行 az vm create 以建立虛擬機。

    az vm create \
      --resource-group myResourceGroup \
      --name myVM \
      --image Debian11 \
      --admin-username azureadmin \
      --generate-ssh-keys \
      --public-ip-sku Standard
    

匯出 Azure 資源

您可以在兩種模式之一中執行 aztfexport 此工具:互動式和非互動式。 在此示範中,您會使用互動式模式。

  1. 建立要在其中測試的目錄。

  2. 開啟命令提示字元並流覽至新的目錄。

  3. 執行 aztfexport resource-group 以匯出名為 myResourceGroup的資源群組。

    aztfexport resource-group myResourceGroup
    
  4. 工具初始化之後,會顯示要導出的資源清單。 每一行都有符合對應 AzureRM 資源類型的 Azure resourceID。 可用的命令清單會顯示在顯示器底部。 使用其中一個命令,捲動至底部,並確認預期的 Azure 資源已正確對應到其各自的 Terraform 資源類型。

    Screenshot showing the Azure resources that would be exported based on the command and resource specified when you run the Azure Export for Terraform tool.

  5. w 以執行匯出。

    重點︰

    • 針對非交互式資源,新增 --non-interactive 旗標: aztfexport rg --non-interactive myResourceGroup

注意

執行適用於 Terraform 的 Azure 匯出可能需要幾分鐘的時間才能完成。

驗證結果

在工具完成匯出 Azure 資源之後,請在包含所產生檔案的相同目錄中執行下列命令。

  1. 執行 terraform init

    terraform init --upgrade
    
  2. 執行 terraform 方案

    terraform plan
    

如果終端機輸出 不需要變更,則恭喜!

您的基礎結構及其對應的狀態已成功匯出至 Terraform。

清除資源

當您不再需要本文中建立的資源時,請執行下列步驟:

  1. 流覽至包含本文 Terraform 檔案的目錄。

  2. 執行 terraform 終結

    terraform destroy
    

下一步