azureterraformazure-resource-managerazure-iot-hubazure-iot-hub-device-management

Terraform Create Azure IoT Device Provisioning Service Enrollment Group


I've been trying to create an Azure IoT Hub Device Provisioning Servince along with Enrollment Group that is using X509 Certificates.

As far as I can see there's no way to do it using azurerm provider. I've also tried to explore azapi options but it seems like type = "Microsoft.Devices/provisioningServices@2022-12-12" also won't be able to offer automatic enrollment group creation?

Is there any other provider I could use for that?


Solution

  • Eventually, I ended up using local_file to create a temporary cert file and then null_resource to run Azure CLI commands, my solution:

    locals {
      iot_hub_name = join("-", [var.project_name, "iothub", var.environment_name])
      dps_name     = join("-", [var.project_name, "dps", var.environment_name])
      cert_path    = "intermediate"
    }
    
    data "azurerm_client_config" "current" {}
    
    resource "azurerm_iothub" "azure_iot_hub" {
    ...
    }
    
    resource "azurerm_iothub_dps" "azure_iot_hub_dps" {
    ...
    }
    
    resource "local_file" "create_cert_file" {
      content  = var.iot_dps_intermediate_cert
      filename = local.cert_path
    }
    
    
    resource "null_resource" "create-dps-certificate-enrollement" {
      provisioner "local-exec" {
        interpreter = ["/bin/bash", "-c"]
        command     = <<-EOT
          az login --service-principal -u $CLIENT_ID -p $CLIENT_SECRET --tenant $TENANT_ID
          az extension add --name azure-iot
          az iot dps enrollment-group create --cp $CERT_PATH -g $RESOURCE_GROUP --dps-name $DPS_NAME --enrollment-id $ENROLLMENT_ID 
        EOT
        environment = {
          CLIENT_ID      = data.azurerm_client_config.current.client_id
          TENANT_ID      = data.azurerm_client_config.current.tenant_id
          CLIENT_SECRET  = var.client_secret
          RESOURCE_GROUP = var.resource_group_name
          DPS_NAME       = local.dps_name
          ENROLLMENT_ID  = "${local.dps_name}-enrollement-group"
          CERT_PATH      = local.cert_path
        }
      }
    
      depends_on = [local_file.create_cert_file]
    }
    

    where var.iot_dps_intermediate_cert represents the content of .pem file that is used to create a new Enrollment Group