快速入门:使用 ARM 模板部署 Azure IoT 中心和存储帐户Quickstart: Deploy an Azure IoT Hub and a storage account using an ARM template

在此快速入门中,你将使用 Azure 资源管理器模板(ARM 模板)创建 IoT 中心以将消息路由到 Azure 存储,并创建存储帐户以保存消息。In this quickstart, you use an Azure Resource Manager template (ARM template) to create an IoT Hub that will route messages to Azure Storage, and a storage account to hold the messages. 将虚拟 IoT 设备手动添加到中心以提交消息后,可在名为“arm-read-write”的应用程序中配置该连接信息,以将该设备的消息提交到中心。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.

ARM 模板是定义项目基础结构和配置的 JavaScript 对象表示法 (JSON) 文件。An ARM template is a JavaScript Object Notation (JSON) file that defines the infrastructure and configuration for your project. 该模板使用声明性语法,使你可以声明要部署的内容,而不需要编写一系列编程命令来进行创建。The template uses declarative syntax, which lets you state what you intend to deploy without having to write the sequence of programming commands to create it.

如果你的环境满足先决条件,并且你熟悉如何使用 ARM 模板,请选择“部署到 Azure”按钮。If your environment meets the prerequisites and you're familiar with using ARM templates, select the Deploy to Azure button. Azure 门户中会打开模板。The template will open in the Azure portal.

部署到 AzureDeploy To Azure

先决条件Prerequisites

如果没有 Azure 订阅,请在开始前创建一个试用 Azure 帐户If you don't have an Azure subscription, create a trial Azure account before you begin.

查看模板Review the template

本快速入门中使用的模板称为 101-iothub-auto-route-messages,来自 Azure 快速入门模板The template used in this quickstart is called 101-iothub-auto-route-messages from Azure Quickstart Templates.

{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "projectName": {
            "type": "string",
            "minLength": 1,
            "maxLength": 11,
            "defaultValue": "contoso",
            "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": "string",
            "defaultValue": "1",
            "metadata": {
                "description": "The number of IoT Hub units."
            }
        },
        "d2cPartitions": {
            "type": "string",
            "defaultValue": "4",
            "metadata": {
                "description": "Partitions used for the event stream."
            }
        }
    },
    "variables": {
        "iotHubName": "[concat(parameters('projectName'), 'Hub', uniqueString(resourceGroup().id))]",
        "storageAccountName": "[concat(toLower(parameters('projectName')), uniqueString(resourceGroup().id))]",
        "storageEndpoint": "[concat(parameters('projectName'), 'StorageEndpont')]",
        "storageContainerName": "[concat(toLower(parameters('projectName')), 'results')]"
    },
    "resources": [
        {
            "type": "Microsoft.Storage/storageAccounts",
            "apiVersion": "2019-06-01",
            "name": "[variables('storageAccountName')]",
            "location": "[parameters('location')]",
            "sku": {
                "name": "Standard_LRS",
                "tier": "Standard"
            },
            "kind": "Storage",
            "properties": {},
            "resources": [
                {
                    "type": "blobServices/containers",
                    "apiVersion": "2019-06-01",
                    "name": "[concat('default/', variables('storageContainerName'))]",
                    "properties": {
                        "publicAccess": "None"
                    },
                    "dependsOn": [
                        "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]"
                    ]
                }
            ]
        },
        {
            "type": "Microsoft.Devices/IotHubs",
            "apiVersion": "2020-03-01",
            "name": "[variables('IoTHubName')]",
            "location": "[parameters('location')]",
            "dependsOn": [
                "[resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName'))]"
            ],
            "properties": {
                "eventHubEndpoints": {
                    "events": {
                        "retentionTimeInDays": 1,
                        "partitionCount": "[parameters('d2cPartitions')]"
                    }
                },
                "routing": {
                    "endpoints": {
                        "storageContainers": [
                            {
                                "connectionString": "[Concat('DefaultEndpointsProtocol=https;AccountName=',variables('storageAccountName'),';EndpointSuffix=',environment().suffixes.storage,';AccountKey=',listKeys(resourceId('Microsoft.Storage/storageAccounts', variables('storageAccountName')), '2019-06-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
                    }
                }
            },
            "sku": {
                "name": "[parameters('skuName')]",
                "capacity": "[parameters('skuUnits')]"
            }
        }
    ],
    "outputs": {
    }
}

该模板中定义了两个 Azure 资源:Two Azure resources are defined in the template:

部署模板并运行示例应用Deploy the template and run the sample app

本部分提供部署模板、创建虚拟设备和运行 arm-read-write 应用程序以发送消息的步骤。This section provides the steps to deploy the template, create a virtual device, and run the arm-read-write application to send the messages.

  1. 通过部署 ARM 模板创建资源。Create the resources by deploying the ARM template.

    提示

    选择下面的按钮以开始部署模板。Select the button below to start the deployment of the template. 在运行时,将 arm-read-write 应用程序设置为运行。While it's running, set up the arm-read-write application to run.

    部署到 AzureDeploy To Azure

  2. 下载并解压缩 IoT C# 示例Download and unzip the IoT C# Samples.

  3. 打开一个命令窗口并转到你将 IoT C# 示例解压缩到的文件夹。Open a command window and go to the folder where you unzipped the IoT C# Samples. 查找包含 arm-read-write.csproj 文件的文件夹。Find the folder with the arm-read-write.csproj file. 可以在此命令窗口中创建环境变量。You create the environment variables in this command window. 登录到 Azure 门户以获取密钥。Log into the Azure portal to get the keys. 选择“资源组”,然后选择用于此快速入门的资源组。Select Resource Groups then select the resource group used for this quickstart.

    选择资源组

  4. 你可以看到部署 ARM 模板时创建的 IoT 中心和存储帐户。You see the IoT Hub and storage account that were created when you deployed the ARM template. 等待模板完全部署后再继续。Wait until the template is fully deployed before continuing. 然后选择资源组以查看资源。Then select your resource group to see your resources.

    查看资源组中的资源

  5. 需要“中心名称”。You need the hub name. 在资源列表中选择中心。Select the hub in the list of resources. 将“IoT 中心”部分顶部的中心名称复制到 Windows 剪贴板。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;
    
  6. 下一个环境变量是 IoT 设备密钥。The next environment variable is the IoT Device Key. 通过从中心的“IoT 中心”菜单中选择“IOT 设备”,将新设备添加到中心。Add a new device to the hub by selecting IOT Devices from the IoT Hub menu for the hub.

    选择 IoT 设备

  7. 在屏幕右侧,选择“+ 新建”以添加新设备。On the right side of the screen, select + NEW to add a new device.

    填写新设备名称。Fill in the new device name. 此快速入门使用以“Contoso-Test-Device”开头的名称。This quickstart uses a name starting with Contoso-Test-Device. 保存设备,然后再次打开该屏幕以检索设备密钥。Save the device and then open that screen again to retrieve the device key. (关闭窗格时将生成密钥。)选择主要或辅助密钥并将其复制到 Windows 剪贴板。(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. 在命令窗口中,设置要执行的命令,然后按 Enter。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>
    
  8. 最后一个环境变量是“设备 ID”。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
    
  9. 若要查看你定义的环境变量,请在命令行中键入 SET 并按 Enter,然后查找以“IoT”开头的变量 。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.

  1. 若要运行应用程序,请在命令窗口中键入以下命令并按 Enter。To run the application, type the following command in the command window and press Enter.

    dotnet run arm-read-write

    应用程序在将每条消息发送到 IoT 中心时在控制台上生成并显示消息。The application generates and displays messages on the console as it sends each message to the IoT hub. 该中心在 ARM 模板中配置为具有自动路由。The hub was configured in the ARM template to have automated routing. 包含文本“level = storage”的消息将自动路由到存储帐户。Messages containing the text "level = storage" are automatically routed to the storage account. 让应用运行 10 到 15 分钟,然后按 Enter 一次或两次,直到它停止运行。Let the app run for 10 to 15 minutes, then press Enter once or twice until it stops running.

查看已部署的资源Review deployed resources

  1. 登录到 Azure 门户,选择资源组,然后选择存储帐户。Log 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.

    查看存储帐户文件

  3. 选择其中一个文件并选择“下载”,将文件下载到你稍后可以找到的位置。Select one of the files and select Download and download the file to a location you can find later. 它会有一个数值名称,比如 47。It will have a name that's numeric, like 47. 在末尾添加“.txt”,然后双击文件打开它。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.

    查看已发送的消息

    备注

    这些消息以 UTF-32 和 base64 编码。These messages are encoded in UTF-32 and base64. 如果读回消息,必须由 base64 和 utf-32 对其进行解码,以便以 ASCII 格式进行读取。If you read the message back, you have to decode it from base64 and utf-32 in order to read it as ASCII. 如果你感兴趣,可以使用路由教程中的 ReadOneRowFromFile 方法从其中某个消息文件对其进行读取,并将其解码为 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 位于你为此快速入门解压缩的 IoT C# 示例存储库中。ReadOneRowFromFile is in the IoT C# Samples repository that you unzipped for this quickstart. 从该文件夹顶层开始的路径为:./iot-hub/Tutorials/Routing/SimulatedDevice/Program.cs。Here is the path from the top of that folder: ./iot-hub/Tutorials/Routing/SimulatedDevice/Program.cs. 将布尔值 readTheFile 设置为 true,并将路径硬编码到磁盘上的文件中,它将打开并转换文件中的第一行。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.

已部署 ARM 模板来创建 IoT 中心和存储帐户,并运行程序来向中心发送消息。You have deployed an ARM template 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

若要删除此快速入门期间添加的资源,请登录到 Azure 门户To remove the resources added during this quickstart, log into the Azure portal. 选择“资源组”,然后查找用于此快速入门的资源组。Select Resource Groups , then find the resource group you used for this quickstart. 选择资源组,然后选择“删除”。Select the resource group and then select Delete. 它将删除组中的所有资源。It will delete all of the resources in the group.

后续步骤Next steps