Quickstart: Deploy an Azure IoT hub and a storage account using an ARM template

In this quickstart, you use an Azure Resource Manager template (ARM template) to create an IoT hub, an Azure Storage account, and a route to send messages from the IoT hub to storage. The hub is configured so the messages sent to the hub are automatically routed to the storage account if they meet the routing condition. At the end of this quickstart, you can open the storage account and see the messages sent.

An Azure Resource Manager template is a JavaScript Object Notation (JSON) file that defines the infrastructure and configuration for your project. The template uses declarative syntax. You describe your intended deployment without writing the sequence of programming commands to create the deployment.

If your environment meets the prerequisites and you're familiar with using ARM templates, select the Deploy to Azure button. The template opens in the Azure portal.

Deploy To Azure

Prerequisites

Review the template

The template used in this quickstart is called 101-iothub-auto-route-messages from Azure Quickstart Templates.

Two Azure resources are defined in the template:

{
  "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "metadata": {
    "_generator": {
      "name": "bicep",
      "version": "0.26.54.24096",
      "templateHash": "1111741482289134864"
    }
  },
  "parameters": {
    "projectName": {
      "type": "string",
      "defaultValue": "contoso",
      "minLength": 1,
      "maxLength": 11,
      "metadata": {
        "description": "Define the project name or prefix for all objects."
      }
    },
    "location": {
      "type": "string",
      "defaultValue": "[resourceGroup().location]",
      "metadata": {
        "description": "The datacenter to use for the deployment."
      }
    },
    "skuName": {
      "type": "string",
      "defaultValue": "S1",
      "metadata": {
        "description": "The SKU to use for the IoT Hub."
      }
    },
    "skuUnits": {
      "type": "int",
      "defaultValue": 1,
      "metadata": {
        "description": "The number of IoT Hub units."
      }
    },
    "d2cPartitions": {
      "type": "int",
      "defaultValue": 4,
      "metadata": {
        "description": "Partitions used for the event stream."
      }
    }
  },
  "variables": {
    "iotHubName": "[format('{0}Hub{1}', parameters('projectName'), uniqueString(resourceGroup().id))]",
    "storageAccountName": "[format('{0}{1}', toLower(parameters('projectName')), uniqueString(resourceGroup().id))]",
    "storageEndpoint": "[format('{0}StorageEndpont', parameters('projectName'))]",
    "storageContainerName": "[format('{0}results', toLower(parameters('projectName')))]"
  },
  "resources": [
    {
      "type": "Microsoft.Storage/storageAccounts",
      "apiVersion": "2023-01-01",
      "name": "[variables('storageAccountName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "Standard_LRS"
      },
      "kind": "Storage",
      "properties": {
        "allowBlobPublicAccess": false,
        "minimumTlsVersion": "TLS1_2",
        "supportsHttpsTrafficOnly": true
      }
    },
    {
      "type": "Microsoft.Storage/storageAccounts/blobServices/containers",
      "apiVersion": "2023-01-01",
      "name": "[format('{0}/default/{1}', variables('storageAccountName'), variables('storageContainerName'))]",
      "properties": {
        "publicAccess": "None"
      },
      "dependsOn": [
        "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]"
      ]
    },
    {
      "type": "Microsoft.Devices/IotHubs",
      "apiVersion": "2023-06-30",
      "name": "[variables('iotHubName')]",
      "location": "[parameters('location')]",
      "sku": {
        "name": "[parameters('skuName')]",
        "capacity": "[parameters('skuUnits')]"
      },
      "properties": {
        "eventHubEndpoints": {
          "events": {
            "retentionTimeInDays": 1,
            "partitionCount": "[parameters('d2cPartitions')]"
          }
        },
        "routing": {
          "endpoints": {
            "storageContainers": [
              {
                "connectionString": "[format('DefaultEndpointsProtocol=https;AccountName={0};EndpointSuffix={1};AccountKey={2}', variables('storageAccountName'), environment().suffixes.storage, listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName')), '2023-01-01').keys[0].value)]",
                "containerName": "[variables('storageContainerName')]",
                "fileNameFormat": "{iothub}/{partition}/{YYYY}/{MM}/{DD}/{HH}/{mm}",
                "batchFrequencyInSeconds": 100,
                "maxChunkSizeInBytes": 104857600,
                "encoding": "JSON",
                "name": "[variables('storageEndpoint')]"
              }
            ]
          },
          "routes": [
            {
              "name": "ContosoStorageRoute",
              "source": "DeviceMessages",
              "condition": "level=\"storage\"",
              "endpointNames": [
                "[variables('storageEndpoint')]"
              ],
              "isEnabled": true
            }
          ],
          "fallbackRoute": {
            "name": "$fallback",
            "source": "DeviceMessages",
            "condition": "true",
            "endpointNames": [
              "events"
            ],
            "isEnabled": true
          }
        },
        "messagingEndpoints": {
          "fileNotifications": {
            "lockDurationAsIso8601": "PT1M",
            "ttlAsIso8601": "PT1H",
            "maxDeliveryCount": 10
          }
        },
        "enableFileUploadNotifications": false,
        "cloudToDevice": {
          "maxDeliveryCount": 10,
          "defaultTtlAsIso8601": "PT1H",
          "feedback": {
            "lockDurationAsIso8601": "PT1M",
            "ttlAsIso8601": "PT1H",
            "maxDeliveryCount": 10
          }
        }
      },
      "dependsOn": [
        "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]"
      ]
    }
  ],
  "outputs": {
    "name": {
      "type": "string",
      "value": "[variables('iotHubName')]"
    },
    "resourceId": {
      "type": "string",
      "value": "[resourceId('Microsoft.Devices/IotHubs', variables('iotHubName'))]"
    },
    "resourceGroupName": {
      "type": "string",
      "value": "[resourceGroup().name]"
    },
    "location": {
      "type": "string",
      "value": "[parameters('location')]"
    }
  }
}

Deploy the template

This section provides the steps to deploy the ARM template.

  • Create the resources by deploying the ARM template.

    Deploy To Azure

Send device-to-cloud messages

In this section, you register a device in your new IoT hub and then send messages from that device to IoT Hub. The route that the template configured in the IoT hub only sends messages to storage if they contain the message property level=storage. To test that this routing condition works as expected, we'll send some messages with that property and some without.

Tip

This quickstart uses the Azure CLI simulated device for convenience. For a code example of sending device-to-cloud messages with message properties for routing, see HubRoutingSample in the Azure IoT SDK for .NET.

  1. Retrieve the name of the IoT hub that the template created for you.

    If you used the default commands in the previous section, your resources were created in the ContosoResourceGrp resource group. If you used a different resource group, update the following command to match.

    az iot hub list --resource-group ContosoResourceGrp --output table
    
  2. Copy the name of your IoT hub from the output. It should be formatted like contosoHub{randomidentifier}

  3. Add a device to the hub.

    az iot hub device-identity create --device-id contosoDevice --hub-name {YourIoTHubName} 
    
  4. Simulate the device and send device-to-cloud messages.

    The --data parameter lets us set the message body.

    az iot device simulate \
      --device-id contosoDevice \
      --hub-name {YourIoTHubName} \
      --data "This message won't be routed."
    

    The simulator sends 100 messages and then disconnects. You don't need to wait for all 100 for the purposes of this quickstart.

    Tip

    The Azure CLI won't print the messages as it sends them. If you want to watch the messages as the arrive at your hub, you can install the Azure IoT Hub extension for Visual Studio Code and use it to monitor the built-in endpoint.

  5. Send device-to-cloud messages to be routed to storage.

    The --properties parameter allows us to add message, application, or system properties to the default message. For this quickstart, the route in your IoT hub is looking for messages that contain the message property level=storage.

    az iot device simulate \
      --device-id contosoDevice \
      --hub-name {YourIoTHubName} \
      --properties level=storage \
      --data "This message will be routed to storage."
    

Review deployed resources

  1. Sign in to the Azure portal and select the Resource Group, then select the storage account.

  2. Drill down into the storage account until you find files.

    Look at the storage account files

  3. Select one of the files and select Download and download the file to a location you can find later. It has a name that's numeric, like 47. Add .txt to the end and then double-click on the file to open it.

  4. When you open the file, each row is for a different message; the body of each message is also encrypted. It must be in order for you to perform queries against the body of the message.

    View the sent messages

    Note

    These messages are encoded in UTF-32 and base64. If you read the message back, you have to decode it from base64 and utf-32 in order to read it as ASCII. If you're interested, you can use the method ReadOneRowFromFile in the Routing Tutorial to read one for from one of these message files and decode it into ASCII. ReadOneRowFromFile is in the IoT C# SDK repository that you unzipped for this quickstart. Here is the path from the top of that folder: ./iothub/device/samples/getting started/RoutingTutorial/SimulatedDevice/Program.cs. Set the boolean readTheFile to true, and hardcode the path to the file on disk, and it will open and translate the first row in the file.

In this quickstart, you deployed an ARM template to create an IoT hub and a storage account, then run a program to send messages to the hub. The messages are routed based on their message properties and stored in the storage account where they can be viewed.

Clean up resources

To remove the resources added during this quickstart, sign in to the Azure portal. Select Resource Groups, then find the resource group you used for this quickstart. Select the resource group and then select Delete. When the group is deleted, so are all of the resources in the group.

Next steps