Share via


快速入門:使用 Terraform 建立 Azure IoT 裝置布建服務

在本快速入門中,您將瞭解如何使用 Terraform 部署具有哈希配置原則的 Azure IoT 中樞 裝置佈建服務 (DPS) 資源。

本快速入門已使用下列 Terraform 和 Terraform 提供者版本進行測試:

Terraform 可讓您定義、預覽和部署雲端基礎結構。 使用 Terraform 時,您可以使用 HCL 語法來建立設定檔。 HCL 語法可讓您指定雲端提供者,例如 Azure,以及構成雲端基礎結構的專案。 建立設定檔之後,您可以建立執行計畫,讓您先預覽基礎結構變更,之後再部署。 驗證變更之後,您可以套用執行計畫來部署基礎結構。

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

  • 建立 儲存體 帳戶和 儲存體 容器
  • 建立事件中樞、命名空間和授權規則
  • 建立 IoT 中樞
  • 將 IoT 中樞 連結至 儲存體 帳戶端點和事件中樞端點
  • 建立 IoT 中樞 共用存取原則
  • 建立 DPS 資源
  • 連結 DPS 和 IoT 中樞

必要條件

  • Azure 訂用帳戶:如果您沒有 Azure 訂用帳戶,請在開始前建立免費帳戶

實作 Terraform 程式碼

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

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

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

    resource "random_pet" "rg_name" {
      prefix = var.resource_group_name_prefix
    }
    
    resource "azurerm_resource_group" "rg" {
      location = var.resource_group_location
      name     = random_pet.rg_name.id
    }
    
    # Create storage account & container
    resource "random_string" "sa_name" {
      length  = 12
      special = false
      upper   = false
    }
    
    resource "azurerm_storage_account" "sa" {
      name                     = random_string.sa_name.id
      resource_group_name      = azurerm_resource_group.rg.name
      location                 = azurerm_resource_group.rg.location
      account_tier             = "Standard"
      account_replication_type = "LRS"
    }
    
    resource "azurerm_storage_container" "my_terraform_container" {
      name                  = "mycontainer"
      storage_account_name  = azurerm_storage_account.sa.name
      container_access_type = "private"
    }
    
    
    # Create an Event Hub & Authorization Rule
    resource "random_pet" "eventhub_namespace_name" {
      prefix = var.eventhub_namespace_name_prefix
    }
    
    resource "azurerm_eventhub_namespace" "namespace" {
      name                = random_pet.eventhub_namespace_name.id
      resource_group_name = azurerm_resource_group.rg.name
      location            = azurerm_resource_group.rg.location
      sku                 = "Basic"
    }
    
    resource "azurerm_eventhub" "my_terraform_eventhub" {
      name                = "myEventHub"
      resource_group_name = azurerm_resource_group.rg.name
      namespace_name      = azurerm_eventhub_namespace.namespace.name
      partition_count     = 2
      message_retention   = 1
    }
    
    resource "azurerm_eventhub_authorization_rule" "my_terraform_authorization_rule" {
      resource_group_name = azurerm_resource_group.rg.name
      namespace_name      = azurerm_eventhub_namespace.namespace.name
      eventhub_name       = azurerm_eventhub.my_terraform_eventhub.name
      name                = "acctest"
      send                = true
    }
    
    
    # Create an IoT Hub
    resource "random_pet" "iothub_name" {
      prefix = var.iothub_name_prefix
      length = 1
    }
    
    resource "azurerm_iothub" "iothub" {
      name                = random_pet.iothub_name.id
      resource_group_name = azurerm_resource_group.rg.name
      location            = azurerm_resource_group.rg.location
    
      sku {
        name     = "S1"
        capacity = 1
      }
    
      endpoint {
        type                       = "AzureIotHub.StorageContainer"
        connection_string          = azurerm_storage_account.sa.primary_blob_connection_string
        name                       = "export"
        batch_frequency_in_seconds = 60
        max_chunk_size_in_bytes    = 10485760
        container_name             = azurerm_storage_container.my_terraform_container.name
        encoding                   = "Avro"
        file_name_format           = "{iothub}/{partition}_{YYYY}_{MM}_{DD}_{HH}_{mm}"
      }
    
      endpoint {
        type              = "AzureIotHub.EventHub"
        connection_string = azurerm_eventhub_authorization_rule.my_terraform_authorization_rule.primary_connection_string
        name              = "export2"
      }
    
      route {
        name           = "export"
        source         = "DeviceMessages"
        condition      = "true"
        endpoint_names = ["export"]
        enabled        = true
      }
    
      route {
        name           = "export2"
        source         = "DeviceMessages"
        condition      = "true"
        endpoint_names = ["export2"]
        enabled        = true
      }
    
      enrichment {
        key            = "tenant"
        value          = "$twin.tags.Tenant"
        endpoint_names = ["export", "export2"]
      }
    
      cloud_to_device {
        max_delivery_count = 30
        default_ttl        = "PT1H"
        feedback {
          time_to_live       = "PT1H10M"
          max_delivery_count = 15
          lock_duration      = "PT30S"
        }
      }
    
      tags = {
        purpose = "testing"
      }
    }
    
    #Create IoT Hub Access Policy
    resource "azurerm_iothub_shared_access_policy" "hub_access_policy" {
      name                = "terraform-policy"
      resource_group_name = azurerm_resource_group.rg.name
      iothub_name         = azurerm_iothub.iothub.name
    
      registry_read   = true
      registry_write  = true
      service_connect = true
    }
    
    # Create IoT Hub DPS
    resource "random_pet" "dps_name" {
      prefix = var.dps_name_prefix
      length = 1
    }
    
    resource "azurerm_iothub_dps" "dps" {
      name                = random_pet.dps_name.id
      resource_group_name = azurerm_resource_group.rg.name
      location            = azurerm_resource_group.rg.location
      allocation_policy   = "Hashed"
    
      sku {
        name     = "S1"
        capacity = 1
      }
    
      linked_hub {
        connection_string       = azurerm_iothub_shared_access_policy.hub_access_policy.primary_connection_string
        location                = azurerm_resource_group.rg.location
        allocation_weight       = 150
        apply_allocation_policy = true
      }
    }
    
  4. 建立名為 variables.tf 的檔案,並插入下列程式碼:

    variable "resource_group_location" {
      default     = "eastus"
      description = "Location of the resource group."
    }
    
    variable "resource_group_name_prefix" {
      default     = "rg"
      description = "Prefix of the resource group name that's combined with a random ID so name is unique in your Azure subscription."
    }
    
    variable "eventhub_namespace_name_prefix" {
      default     = "namespace"
      description = "Prefix of the event hub namespace name that's combined with a random ID so name is unique in your Azure subscription."
    }
    
    variable "iothub_name_prefix" {
      default     = "iothub"
      description = "Prefix of the iot hub name that's combined with a random ID so name is unique in your Azure subscription."
    }
    
    variable "dps_name_prefix" {
      default     = "dps"
      description = "Prefix of the dps name that's combined with a random ID so name is unique in your Azure subscription."
    }
    
  5. 建立名為 outputs.tf 的檔案,並插入下列程式碼:

    output "azurerm_iothub_name" {
      value = azurerm_iothub.iothub.name
    }
    
    output "azurerm_iothub_dps_name" {
      value = azurerm_iothub_dps.dps.name
    }
    
    output "resource_group_name" {
      value = azurerm_resource_group.rg.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,不需要使用參數。

驗證結果

執行 az iot dps show 以顯示 Azure DPS 資源。

az iot dps show \
   --name <azurerm_iothub_dps_name> \
   --resource-group <resource_group_name>

重點︰

  • 資源群組和 DPS 實例的名稱會顯示在輸出中 terraform apply 。 您也可以執行 terraform 輸出 來檢視這些輸出值。

清除資源

當您不再需要透過 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 時的常見問題進行疑難排解

下一步

在本快速入門中,您已部署IoT中樞和裝置布建服務實例,並連結這兩個資源。 若要瞭解如何使用此設定來布建裝置,請繼續進行建立裝置的快速入門。