Quickstart: Deploy an Azure IoT hub and a storage account using Bicep
In this quickstart, you use Bicep to create an IoT hub that will route messages to Azure Storage and a storage account to hold the messages. After manually adding a virtual IoT device to the hub to submit the messages, you configure that connection information in an application called arm-read-write to submit messages from the device to the hub. The hub is configured so the messages sent to the hub are automatically routed to the storage account. At the end of this quickstart, you can open the storage account and see the messages sent.
Bicep is a domain-specific language (DSL) that uses declarative syntax to deploy Azure resources. It provides concise syntax, reliable type safety, and support for code reuse. Bicep offers the best authoring experience for your infrastructure-as-code solutions in Azure.
Prerequisites
If you don't have an Azure subscription, create a free Azure account before you begin.
Review the Bicep file
The Bicep file used in this quickstart is called 101-iothub-auto-route-messages
from Azure Quickstart Templates.
@description('Define the project name or prefix for all objects.')
@minLength(1)
@maxLength(11)
param projectName string = 'contoso'
@description('The datacenter to use for the deployment.')
param location string = resourceGroup().location
@description('The SKU to use for the IoT Hub.')
param skuName string = 'S1'
@description('The number of IoT Hub units.')
param skuUnits int = 1
@description('Partitions used for the event stream.')
param d2cPartitions int = 4
var iotHubName = '${projectName}Hub${uniqueString(resourceGroup().id)}'
var storageAccountName = '${toLower(projectName)}${uniqueString(resourceGroup().id)}'
var storageEndpoint = '${projectName}StorageEndpont'
var storageContainerName = '${toLower(projectName)}results'
resource storageAccount 'Microsoft.Storage/storageAccounts@2021-08-01' = {
name: storageAccountName
location: location
sku: {
name: 'Standard_LRS'
}
kind: 'Storage'
}
resource container 'Microsoft.Storage/storageAccounts/blobServices/containers@2021-08-01' = {
name: '${storageAccountName}/default/${storageContainerName}'
properties: {
publicAccess: 'None'
}
dependsOn: [
storageAccount
]
}
resource IoTHub 'Microsoft.Devices/IotHubs@2021-07-02' = {
name: iotHubName
location: location
sku: {
name: skuName
capacity: skuUnits
}
properties: {
eventHubEndpoints: {
events: {
retentionTimeInDays: 1
partitionCount: d2cPartitions
}
}
routing: {
endpoints: {
storageContainers: [
{
connectionString: 'DefaultEndpointsProtocol=https;AccountName=${storageAccountName};EndpointSuffix=${environment().suffixes.storage};AccountKey=${storageAccount.listKeys().keys[0].value}'
containerName: storageContainerName
fileNameFormat: '{iothub}/{partition}/{YYYY}/{MM}/{DD}/{HH}/{mm}'
batchFrequencyInSeconds: 100
maxChunkSizeInBytes: 104857600
encoding: 'JSON'
name: storageEndpoint
}
]
}
routes: [
{
name: 'ContosoStorageRoute'
source: 'DeviceMessages'
condition: 'level="storage"'
endpointNames: [
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
}
}
}
}
Two Azure resources are defined in the Bicep file:
Deploy the Bicep file and run the sample app
This section provides the steps to deploy the Bicep file, create a virtual device, and run the arm-read-write application to send the messages.
Create the resources by deploying the Bicep file using Azure CLI or Azure PowerShell.
az group create --name ContosoResourceGrp --location eastus az deployment group create --resource-group exampleRG --template-file main.bicep
When the deployment finishes, you should see a message indicating the deployment succeeded.
Download and unzip the IoT C# SDK.
Open a command window and go to the folder where you unzipped the IoT C# SDK. Find the folder with the arm-read-write.csproj file. You create the environment variables in this command window. Sign in to the Azure portal to get the keys. Select Resource Groups then select the resource group used for this quickstart.
You see the IoT Hub and storage account that were created when you deployed the Bicep file. Wait until the file is fully deployed before continuing. Then select your resource group to see your resources.
You need the hub name. Select the hub in the list of resources. Copy the name of the hub from the top of the IoT Hub section to the Windows clipboard.
Substitute the hub name in this command where noted, and execute this command in the command window:
SET IOT_HUB_URI=<hub name goes here>.azure-devices-net;
which will look this example:
SET IOT_HUB_URI=ContosoTestHubdlxlud5h.azure-devices-net;
The next environment variable is the IoT Device Key. Add a new device to the hub by selecting Devices from the IoT Hub menu for the hub.
On the right side of the screen, select + Add Device to add a new device.
Fill in the new device name. This quickstart uses a name starting with Contoso-Test-Device. Save the device and then open that screen again to retrieve the device key. (The key is generated for you when you close the pane.) Select either the primary or secondary key and copy it to the Windows clipboard. In the command window, set the command to execute and then press Enter. The command should look like this one but with the device key pasted in:
SET IOT_DEVICE_KEY=<device-key-goes-here>
The last environment variable is the Device ID. In the command window, set up the command and execute it.
SET IOT_DEVICE_ID=<device-id-goes-here>
which will look like this example:
SET IOT_DEVICE_ID=Contoso-Test-Device
To see the environment variables you've defined, type SET on the command line and press Enter, then look for the ones starting with IoT.
Now the environment variables are set, run the application from the same command window. Because you're using the same window, the variables will be accessible in memory when you run the application.
To run the application, type the following command in the command window and press Enter.
dotnet run arm-read-write
The application generates and displays messages on the console as it sends each message to the IoT hub. The hub was configured in the Bicep file to have automated routing. Messages containing the text
level = storage
are automatically routed to the storage account. Let the app run for 10 to 15 minutes, then press Enter once or twice until it stops running.
Review deployed resources
Sign in to the Azure portal and select the Resource Group, then select the storage account.
Drill down into the storage account until you find files.
Select one of the files and select Download and download the file to a location you can find later. It will have a name that's numeric, like 47. Add .txt to the end and then double-click on the file to open it.
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.
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.
You have deployed a Bicep file to create an IoT hub and a storage account, and run a program to send messages to the hub. The messages are then automatically stored in the storage account where they can be viewed.
Clean up resources
When you no longer need the resources that you created, delete the resource group.
az group delete --name exampleRG
Next steps
Feedback
Submit and view feedback for