共用方式為


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

在這個快速入門中,你將學習如何使用 Terraform 部署帶有雜湊配置政策的 Azure IoT Hub 裝置配置服務(DPS)資源。

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

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

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

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

先決條件

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

實作 Terraform 程式碼

備註

本文中的範例程式代碼位於 Azure Terraform GitHub 存放庫。 欲了解更多資訊,包括如何使用 Terraform 管理 Azure 資源的文章與範例程式碼,請參閱 Terraform on Azure 文件

  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 計劃 以建立執行計劃。

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 計劃 並指定 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 中樞和裝置佈建服務執行個體,並已連結這兩個資源。 若要了解如何使用這項設定來佈建裝置,請繼續進行建立裝置的快速入門。