如何将 Azure IoT 中心克隆到另一个区域How to clone an Azure IoT hub to another region

本文探讨克隆 IoT 中心的方法,并提供在开始之前需要回答的一些问题。This article explores ways to clone an IoT Hub and provides some questions you need to answer before you start. 下面是克隆 IoT 中心的几个可能原因:Here are several reasons you might want to clone an IoT hub:

  • 要将公司从一个区域迁移到另一个区域(例如,从中国东部到中国北部,或反之),并希望自己的资源和数据在地理上靠近新位置,因此需要迁移中心。You are moving your company from one region to another, such as from China East to China North (or vice versa), and you want your resources and data to be geographically close to your new location, so you need to move your hub.

  • 要为开发环境和生产环境设置中心。You are setting up a hub for a development versus production environment.

  • 要以自定义方式实现多中心高可用性。You want to do a custom implementation of multi-hub high availability. 有关详细信息,请参阅“IoT 中心高可用性和灾难恢复”中的“如何实现跨区域高可用性”部分For more information, see the How to achieve cross region HA section of IoT Hub high availability and disaster recovery.

  • 需要增加为中心配置的分区数。You want to increase the number of partitions configured for your hub. 此数目是首次创建中心时设置的,以后无法更改。This is set when you first create your hub, and can't be changed. 可以使用本文所述的信息来克隆中心,并在创建克隆时增加分区数。You can use the information in this article to clone your hub and when the clone is created, increase the number of partitions.

若要克隆中心,需要一个对原始中心拥有管理访问权限的订阅。To clone a hub, you need a subscription with administrative access to the original hub. 可将新的中心放到新的资源组和区域、原始中心所在的同一订阅甚至新的订阅中。You can put the new hub in a new resource group and region, in the same subscription as the original hub, or even in a new subscription. 不能使用相同的名称,因为中心名称必须全局唯一。You just can't use the same name because the hub name has to be globally unique.


目前,没有可用于自动克隆 IoT 中心的功能。At this time, there's no feature available for cloning an IoT hub automatically. 克隆主要是一个手动过程,因此非常容易出错。It's primarily a manual process, and thus is fairly error-prone. 克隆中心的复杂性与中心的复杂性直接相关。The complexity of cloning a hub is directly proportional to the complexity of the hub. 例如,克隆不带消息路由的 IoT 中心就非常简单。For example, cloning an IoT hub with no message routing is fairly simple. 如果添加消息路由,这看上去只是在一个方面提高了复杂性,但克隆中心的复杂性至少会提高一个数量级。If you add message routing as just one complexity, cloning the hub becomes at least an order of magnitude more complicated. 如果同时还要移动用于路由终结点的资源,则复杂性又会提高一个数量级。If you also move the resources used for routing endpoints, it's another order of magniture more complicated.

注意事项Things to consider

在克隆 IoT 中心之前,需要考虑几个要点。There are several things to consider before cloning an IoT hub.

  • 确保原始位置中所有可用的功能在新位置中也可用。Make sure that all of the features available in the original location are also available in the new location. 某些服务以预览版提供,因此并非所有功能都可以在任何位置使用。Some services are in preview, and not all features are available everywhere.

  • 在创建和验证已克隆的版本之前不要删除原始资源。Do not remove the original resources before creating and verifying the cloned version. 一旦删除某个中心,就会将其永久删除,并且没有任何办法可以恢复,因此也就无法检查设置或数据来确保复制正确中心。Once you remove a hub, it's gone forever, and there is no way to recover it to check the settings or data to make sure the hub is replicated correctly.

  • 许多资源需要全局唯一的名称,因此必须对克隆的版本使用不同的名称。Many resources require globally unique names, so you must use different names for the cloned versions. 此外,应该对克隆的中心所属的资源组使用不同的名称。You also should use a different name for the resource group to which the cloned hub belongs.

  • 原始 IoT 中心的数据不会迁移。Data for the original IoT hub is not migrated. 这包括遥测消息、云到设备 (C2D) 的命令,以及作业相关的信息,例如计划和历史记录。This includes telemetry messages, cloud-to-device (C2D) commands, and job-related information such as schedules and history. 指标和日志记录结果也不会迁移。Metrics and logging results are also not migrated.

  • 对于路由到 Azure 存储的数据或消息,可将数据保留在原始存储帐户中,将该数据传输到新区域中的新存储帐户,或者将旧数据保留在原位,并在新位置为新数据创建新存储帐户。For data or messages routed to Azure Storage, you can leave the data in the original storage account, transfer that data to a new storage account in the new region, or leave the old data in place and create a new storage account in the new location for the new data. 有关在 Blob 存储中移动数据的详细信息,请参阅 AzCopy 入门For more information on moving data in Blob storage, see Get started with AzCopy.

  • 无法迁移事件中心以及服务总线主题和队列的数据。Data for Event Hubs and for Service Bus Topics and Queues can't be migrated. 这些数据属于时间点数据,在处理消息后不会存储。This is point-in-time data and is not stored after the messages are processed.

  • 需要针对迁移造成的停机时间做好安排。You need to schedule downtime for the migration. 将设备克隆到新中心需要花费一定的时间。Cloning the devices to the new hub takes time. 如果使用导入/导出方法,基准测试表明,移动 500,000 个设备可能需要大约两个小时,而移动 100 万个设备大约需要四个小时。If you are using the Import/Export method, benchmark testing has revealed that it could take around two hours to move 500,000 devices, and four hours to move a million devices.

  • 无需关闭或更改设备,即可将设备复制到新中心。You can copy the devices to the new hub without shutting down or changing the devices.

    • 如果设备最初是使用 DPS 预配的,则重新预配它们会更新每个设备中存储的连接信息。If the devices were originally provisioned using DPS, re-provisioning them updates the connection information stored in each device.

    • 否则,必须使用导入/导出方法来移动设备,然后必须修改设备才能使用新中心。Otherwise, you have to use the Import/Export method to move the devices, and then the devices have to be modified to use the new hub. 例如,可将设备设置为使用孪生所需属性中的 IoT 中心主机名。For example, you can set up your device to consume the IoT Hub host name from the twin desired properties. 设备将采用该 IoT 中心主机名,从旧中心断开设备的连接,然后将设备重新连接到新中心。The device will take that IoT Hub host name, disconnect the device from the old hub, and reconnect it to the new one.

  • 需要更新所用的任何证书,以便可将其用于新资源。You need to update any certificates you are using so you can use them with the new resources. 此外,你可能已在 DNS 表中的某个位置定义了中心 — 在这种情况下,需要更新这些 DNS 信息。Also, you probably have the hub defined in a DNS table somewhere — you will need to update that DNS information.


下面是我们建议的将 IoT 中心从一个区域移到另一个区域的常规方法。This is the general method we recommend for moving an IoT hub from one region to another. 对于消息路由,此方法假设不会将资源移到新区域。For message routing, this assumes the resources are not being moved to the new region. 有关详细信息,请参阅有关消息路由的部分For more information, see the section on Message Routing.

  1. 将中心及其设置导出到资源管理器模板。Export the hub and its settings to a Resource Manager template.

  2. 对模板进行所需的更改,例如,更新克隆的中心的所有现有名称和位置。Make the necessary changes to the template, such as updating all occurrences of the name and the location for the cloned hub. 对于模板中用于消息路由终结点的任何资源,请在模板中更新该资源的密钥。For any resources in the template used for message routing endpoints, update the key in the template for that resource.

  3. 将模板导入到位于新位置的新资源组。Import the template into a new resource group in the new location. 这会创建克隆。This creates the clone.

  4. 请根据需要进行调试。Debug as needed.

  5. 添加未导出到模板中的任何内容。Add anything that wasn't exported to the template.

    例如,使用者组就不会导出到模板中。For example, consumer groups are not exported to the template. 需要手动将使用者组添加到模板中,或者在创建中心后使用 Azure 门户来添加。You need to add the consumer groups to the template manually or use the Azure portal after the hub is created.

  6. 将原始中心内的设备复制到克隆中。Copy the devices from the original hub to the clone. 管理已注册到 IoT 中心的设备部分介绍了此操作。This is covered in the section Managing the devices registered to the IoT hub.

如何处理消息路由How to handle message routing

如果中心使用自定义路由,则导出中心模板的过程涉及路由配置,但不涉及资源本身。If your hub uses custom routing, exporting the template for the hub includes the routing configuration, but it does not include the resources themselves. 必须选择是要将路由资源移到新位置,还是将其保留在原地,并“按原样”继续使用它们。You must choose whether to move the routing resources to the new location or to leave them in place and continue to use them "as is".

例如,假设你在中国北部的一个中心会将消息路由到同样位于中国北部的存储帐户,而你希望将中心移到中国东部。For example, say you have a hub in China North that is routing messages to a storage account (also in China North), and you want to move the hub to China East. 可以移动该中心,并让它继续将消息路由到中国北部的存储帐户,或者,可以同时移动该中心和存储帐户。You can move the hub and have it still route messages to the storage account in China North, or you can move the hub and also move the storage account. 将消息路由到不同区域中的终结点资源可能会导致性能轻微下降。There may be a small performance hit from routing messages to endpoint resources in a different region.

如果不同时移动用于路由终结点的资源,则移动使用消息路由的中心就相当简单。You can move a hub that uses message routing pretty easily if you do not also move the resources used for the routing endpoints.

如果中心使用消息路由,你可以采用两种做法。If the hub uses message routing, you have two choices.

  1. 将用于路由终结点的资源移到新位置。Move the resources used for the routing endpoints to the new location.

    • 必须在 Azure 门户中或通过资源管理器模板自行手动创建新资源。You must create the new resources yourself either manually in the Azure portal or through the use of Resource Manager templates.

    • 在新位置创建资源时,必须重命名所有资源,因为它们具有全局唯一的名称。You must rename all of the resources when you create them in the new location, as they have globally unique names.

    • 在创建新中心之前,必须在新中心的模板中更新资源名称和资源密钥。You must update the resource names and the resource keys in the new hub's template, before creating the new hub. 创建新中心时,这些资源应该存在。The resources should be present when the new hub is created.

  2. 不要移动用于路由终结点的资源。Don't move the resources used for the routing endpoints. 请“在原地”使用这些资源。Use them "in place".

    • 在编辑模板的步骤中,需要检索每个路由资源的密钥并将其放入模板,然后再创建新中心。In the step where you edit the template, you will need to retrieve the keys for each routing resource and put them in the template before you create the new hub.

    • 中心仍引用原始路由资源,并按配置将消息路由到这些资源。The hub still references the original routing resources and routes messages to them as configured.

    • 由于中心和路由终结点资源不在同一位置,因此性能会略微下降。You will have a small performance hit because the hub and the routing endpoint resources are not in the same location.

准备将中心迁移到另一个区域Prepare to migrate the hub to another region

本部分提供有关迁移中心的具体说明。This section provides specific instructions for migrating the hub.

找到原始中心并将其导出到资源模板。Find the original hub and export it to a resource template.

  1. 登录到 Azure 门户Sign into the Azure portal.

  2. 转到“资源组”,选择包含所要移动的中心的资源组。 Go to Resource Groups and select the resource group that contains the hub you want to move. 也可以转到“资源”并找到该中心。 You can also go to Resources and find the hub that way. 选择该中心。Select the hub.

  3. 从中心的属性和设置列表中选择“导出模板”。 Select Export template from the list of properties and settings for the hub.

    显示用于导出 IoT 中心模板的命令的屏幕截图。

  4. 选择“下载”以下载模板。 Select Download to download the template. 将文件保存到可以再次找到的某个位置。Save the file somewhere you can find it again.

    显示用于下载 IoT 中心模板的命令的屏幕截图。

查看模板View the template

  1. 转到“下载”文件夹(或导出模板时使用的任何文件夹),并找到下载的 zip 文件。Go to the Downloads folder (or to whichever folder you used when you exported the template) and find the zip file. 打开该 zip 文件,找到名为 template.json 的文件。Open the zip file and find the file called template.json. 选择该文件,然后按 Ctrl+C 复制模板。Select it, then select Ctrl+C to copy the template. 转到不在 zip 文件中的另一文件夹,然后粘贴该文件 (Ctrl+V)。Go to a different folder that's not in the zip file and paste the file (Ctrl+V). 现在可对其进行编辑。Now you can edit it.

    以下示例适用于没有路由配置的一般中心。The following example is for a generic hub with no routing configuration. 它是 chinaeast 区域中名为 ContosoTestHub29358 的一个 S1 层中心(具有 1 个单元)。It is an S1 tier hub (with 1 unit) called ContosoTestHub29358 in region chinaeast. 下面是导出的模板。Here is the exported template.

        "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
        "contentVersion": "",
        "parameters": {
            "IotHubs_ContosoTestHub29358_name": {
                "defaultValue": "ContosoTestHub29358",
                "type": "String"
        "variables": {},
        "resources": [
                "type": "Microsoft.Devices/IotHubs",
                "apiVersion": "2018-04-01",
                "name": "[parameters('IotHubs_ContosoTestHub29358_name')]",
                "location": "chinaeast",
                "sku": {
                    "name": "S1",
                    "tier": "Standard",
                    "capacity": 1
                "properties": {
                    "operationsMonitoringProperties": {
                        "events": {
                            "None": "None",
                            "Connections": "None",
                            "DeviceTelemetry": "None",
                            "C2DCommands": "None",
                            "DeviceIdentityOperations": "None",
                            "FileUploadOperations": "None",
                            "Routes": "None"
                    "ipFilterRules": [],
                    "eventHubEndpoints": {
                        "events": {
                            "retentionTimeInDays": 1,
                            "partitionCount": 2,
                            "partitionIds": [
                            "path": "contosotesthub29358",
                            "endpoint": "sb://iothub-ns-contosotes-2227755-92aefc8b73.servicebus.windows.net/"
                        "operationsMonitoringEvents": {
                            "retentionTimeInDays": 1,
                            "partitionCount": 2,
                            "partitionIds": [
                            "path": "contosotesthub29358-operationmonitoring",
                            "endpoint": "sb://iothub-ns-contosotes-2227755-92aefc8b73.servicebus.windows.net/"
                    "routing": {
                        "endpoints": {
                            "serviceBusQueues": [],
                            "serviceBusTopics": [],
                            "eventHubs": [],
                            "storageContainers": []
                        "routes": [],
                        "fallbackRoute": {
                            "name": "$fallback",
                            "source": "DeviceMessages",
                            "condition": "true",
                            "endpointNames": [
                            "isEnabled": true
                    "storageEndpoints": {
                        "$default": {
                            "sasTtlAsIso8601": "PT1H",
                            "connectionString": "",
                            "containerName": ""
                    "messagingEndpoints": {
                        "fileNotifications": {
                            "lockDurationAsIso8601": "PT1M",
                            "ttlAsIso8601": "PT1H",
                            "maxDeliveryCount": 10
                    "enableFileUploadNotifications": false,
                    "cloudToDevice": {
                        "maxDeliveryCount": 10,
                        "defaultTtlAsIso8601": "PT1H",
                        "feedback": {
                            "lockDurationAsIso8601": "PT1M",
                            "ttlAsIso8601": "PT1H",
                            "maxDeliveryCount": 10
                    "features": "None"

编辑模板Edit the template

必须先进行一些更改,然后才能使用该模板在新区域中创建新中心。You have to make some changes before you can use the template to create the new hub in the new region. 使用 VS Code 或文本编辑器来编辑该模板。Use VS Code or a text editor to edit the template.

编辑中心名称和位置Edit the hub name and location

  1. 删除顶部的 parameters 节 -- 只使用中心名称可以大大简化操作,因为我们不会使用多个参数。Remove the parameters section at the top -- it is much simpler to just use the hub name because we're not going to have multiple parameters.

        "parameters": {
            "IotHubs_ContosoTestHub29358_name": {
                "defaultValue": "ContosoTestHub29358",
                "type": "String"
  2. 更改名称以使用实际(新)名称,而无需从参数(在上一步骤中已删除参数)中检索该名称。Change the name to use the actual (new) name rather than retrieving it from a parameter (which you removed in the previous step).

    对于新中心,请使用原始中心的名称加上字符串 clone 来构成新的名称。For the new hub, use the name of the original hub plus the string clone to make up the new name. 首先清理中心名称和位置。Start by cleaning up the hub name and location.

    旧版本:Old version:

    "name": "[parameters('IotHubs_ContosoTestHub29358_name')]",
    "location": "chinaeast",

    新版本:New version:

    "name": "ContosoTestHub29358clone",
    "location": "eastus",

    接下来,你会发现 path 的值包含旧中心的名称。Next, you'll find that the values for path contain the old hub name. 请将这些值更改为使用新名称。Change them to use the new one. 下面是 eventHubEndpoints 下的名为 eventsOperationsMonitoringEvents 的路径值。These are the path values under eventHubEndpoints called events and OperationsMonitoringEvents.

    完成后,事件中心终结点节应如下所示:When you're done, your event hub endpoints section should look like this:

    "eventHubEndpoints": {
        "events": {
            "retentionTimeInDays": 1,
            "partitionCount": 2,
            "partitionIds": [
            "path": "contosotesthub29358clone",
            "endpoint": "sb://iothub-ns-contosotes-2227755-92aefc8b73.servicebus.windows.net/"
        "operationsMonitoringEvents": {
            "retentionTimeInDays": 1,
            "partitionCount": 2,
            "partitionIds": [
            "path": "contosotesthub29358clone-operationmonitoring",
            "endpoint": "sb://iothub-ns-contosotes-2227755-92aefc8b73.servicebus.windows.net/"

更新不移动的路由资源的密钥Update the keys for the routing resources that are not being moved

导出已配置路由的中心的资源管理器模板时,将会看到,导出的模板中并未提供这些资源的密钥 -- 这些密钥所在的位置由星号代替。When you export the Resource Manager template for a hub that has routing configured, you will see that the keys for those resources are not provided in the exported template -- their placement is denoted by asterisks. 在导入新中心的模板并创建该中心之前,必须在门户中转到这些资源并检索密钥,然后填充密钥。You must fill them in by going to those resources in the portal and retrieving the keys before you import the new hub's template and create the hub.

  1. 检索所有路由资源所需的密钥,并将其放到模板中。Retrieve the keys required for any of the routing resources and put them in the template. 可以从 Azure 门户中的资源检索密钥。You can retrieve the key(s) from the resource in the Azure portal.

    例如,如果要将消息路由到某个存储容器,请在门户中找到相应的存储帐户。For example, if you are routing messages to a storage container, find the storage account in the portal. 在“设置”部分下选择“访问密钥”,然后复制其中的一个密钥。 Under the Settings section, select Access keys, then copy one of the keys. 首次导出模板时,密钥如下所示:Here's what the key looks like when you first export the template:

    "connectionString": "DefaultEndpointsProtocol=https;
    "containerName": "fabrikamresults",
  2. 检索存储帐户的帐户密钥后,请将其输入到模板上的子句 AccountKey=**** 中,并取代星号。After you retrieve the account key for the storage account, put it in the template in the clause AccountKey=**** in the place of the asterisks.

  3. 对于服务总线队列,获取与 SharedAccessKeyName 匹配的共享访问密钥。For service bus queues, get the Shared Access Key matching the SharedAccessKeyName. 下面是 JSON 中的密钥和 SharedAccessKeyNameHere is the key and the SharedAccessKeyName in the json:

    "connectionString": "Endpoint=sb://fabrikamsbnamespace1234.servicebus.windows.net:5671/;
  4. 上述操作对于服务总线主题和事件中心连接也适用。The same applies for the Service Bus Topics and Event Hub connections.

在新位置创建新的路由资源Create the new routing resources in the new location

仅当移动中心对路由终结点使用的资源时,本部分的内容才适用。This section only applies if you are moving the resources used by the hub for the routing endpoints.

若要移动路由资源,必须在新位置手动设置资源。If you want to move the routing resources, you must manually set up the resources in the new location. 可以使用 Azure 门户创建路由资源,或者导出消息路由使用的每个资源的资源管理器模板,对其进行编辑,然后导入此模板。You can create the routing resources using the Azure portal, or by exporting the Resource Manager template for each of the resources used by the message routing, editing them, and importing them. 设置资源后,可以导入中心的模板(包括路由配置)。After the resources are set up, you can import the hub's template (which includes the routing configuration).

  1. 创建路由使用的每个资源。Create each resource used by the routing. 可以使用 Azure 门户手动执行此操作,也可以使用资源管理器模板创建资源。You can do this manually using the Azure portal, or create the resources using Resource Manager templates. 若要使用模板,请执行以下步骤:If you want to use templates, these are the steps to follow:

    1. 对于路由使用的每个资源,请将其导出到资源管理器模板。For each resource used by the routing, export it to a Resource Manager template.

    2. 更新资源的名称和位置。Update the name and location of the resource.

    3. 更新资源之间的任何交叉引用。Update any cross-references between the resources. 例如,如果为新存储帐户创建模板,则需要更新该模板中的存储帐户名称,以及引用该名称的其他任何模板。For example, if you create a template for a new storage account, you need to update the storage account name in that template and any other template that references it. 在大多数情况下,只有中心模板中的 routing 节才是引用资源的模板。In most cases, the routing section in the template for the hub is the only other template that references the resource.

    4. 导入每个模板,以部署每个资源。Import each of the templates, which deploys each resource.

    设置并运行路由使用的资源后,可以继续操作。Once the resources used by the routing are set up and running, you can continue.

  2. 在 IoT 中心的模板中,将每个路由资源的名称更改为新名称,并根据需要更新位置。In the template for the IoT hub, change the name of each of the routing resources to its new name, and update the location if needed.

现已设置好一个模板,它可以根据你确定的路由处理方式,创建一个在外观上几乎与旧中心完全一致的新中心。Now you have a template that will create a new hub that looks almost exactly like the old hub, depending on how you decided to handle the routing.

移动 -- 通过加载模板在新区域中创建新中心Move -- create the new hub in the new region by loading the template

使用模板在新位置创建新中心。Create the new hub in the new location using the template. 若要移动路由资源,应在新位置设置资源,并更新模板中的引用,以使其匹配。If you have routing resources that are going to move, the resources should be set up in the new location and the references in the template updated to match. 如果不移动路由资源,应将其包含在模板中并对其使用更新的密钥。If you are not moving the routing resources, they should be in the template with the updated keys.

  1. 登录到 Azure 门户Sign into the Azure portal.

  2. 选择“创建资源”。 Select Create a resource.

  3. 在搜索框中输入“模板部署”,然后按 Enter。In the search box, put in "template deployment" and select Enter.

  4. 选择“模板部署(使用自定义模板进行部署)”。 Select template deployment (deploy using custom templates). 随后会转到“模板部署”屏幕。This takes you to a screen for the Template deployment. 选择“创建” 。Select Create. 将看到以下屏幕:You see this screen:


  5. 选择“在编辑器中生成自己的模板”,以便可以从文件上传模板。 Select Build your own template in the editor, which enables you to upload your template from a file.

  6. 选择“加载文件”。 Select Load file.


  7. 浏览到已编辑的新模板并将其选中,然后选择“打开”。 Browse for the new template you edited and select it, then select Open. 随即会在编辑窗口中加载该模板。It loads your template in the edit window. 选择“保存” 。Select Save.


  8. 在以下字段中进行填充。Fill in the following fields.

    订阅:选择要使用的订阅。Subscription: select the subscription to use.

    资源组:在新位置创建新资源组。Resource group: create a new resource group in a new location. 如果已经设置了新的资源组,可以选择它,而无需新建。If you already have a new one set up, you can select it instead of creating a new one.

    位置:如果选择了现有的资源组,则系统会自动填充与该资源组匹配的位置。Location: If you selected an existing resource group, this is filled in for you to match the location of the resource group. 如果创建了新资源组,请填充其位置。If you created a new resource group, this will be its location.

    “我同意”复选框:简单而言,选中此框表示你同意为创建的资源付费。I agree checkbox: this basically says that you agree to pay for the resource(s) you're creating.

  9. 选择“购买”按钮。 Select the Purchase button.

门户现在会验证该模板并部署克隆的中心。The portal now validates your template and deploys your cloned hub. 如果有路由配置数据,该数据将包含到新中心,但会指向位于先前位置的资源。If you have routing configuration data, it will be included in the new hub, but will point at the resources in the prior location.

管理已注册到 IoT 中心的设备Managing the devices registered to the IoT hub

启动并运行克隆后,接下来需要将原始中心内的所有设备复制到该克隆。Now that you have your clone up and running, you need to copy all of the devices from the original hub to the clone.

可通过多种方法来实现此目的。There are multiple ways to accomplish this. 具体方法取决于最初是否使用设备预配服务 (DPS) 预配了设备。You either originally used Device Provisioning Service (DPS)to provision the devices, or you didn't. 如果是,则操作并不困难。If you did, this is not difficult. 如果不是,操作可能十分复杂。If you did not, this can be very complicated.

如果未使用 DPS 预配设备,可以跳过下一部分,并开始使用导入/导出功能将设备移到新中心If you did not use DPS to provision your devices, you can skip the next section and start with Using Import/Export to move the devices to the new hub.

使用 DPS 在新中心重新预配设备Using DPS to re-provision the devices in the new hub

若要使用 DPS 将设备移到新位置,请参阅如何重新预配设备To use DPS to move the devices to the new location, see How to re-provision devices. 完成后,可以在 Azure 门户中查看设备,并确认它们是否出现在新位置。When you're finished, you can view the devices in the Azure portal and verify they are in the new location.

使用 Azure 门户转到新中心。Go to the new hub using the Azure portal. 选择该中心,然后选择“IoT 设备”。 Select your hub, then select IoT Devices. 将会看到已重新预配到克隆的中心的设备。You see the devices that were re-provisioned to the cloned hub. 还可以查看克隆的中心的属性。You can also view the properties for the cloned hub.

如果已实施路由,请测试并确保将消息正确路由到资源。If you have implemented routing, test and make sure your messages are routed to the resources correctly.

使用 DPS 后提交更改Committing the changes after using DPS

此项更改已由 DPS 服务提交。This change has been committed by the DPS service.

使用 DPS 后回滚更改。Rolling back the changes after using DPS.

若要回滚更改,请将设备从新中心重新预配到旧中心。If you want to roll back the changes, re-provision the devices from the new hub to the old one.

现已完成迁移中心及其设备的过程。You are now finished migrating your hub and its devices. 接下来可以跳到清理部分。You can skip to Clean-up.

使用导入/导出功能将设备移到新中心Using Import-Export to move the devices to the new hub

应用程序面向 .NET Core,因此可以在 Windows 或 Linux 上运行它。The application targets .NET Core, so you can run it on either Windows or Linux. 可以下载示例,检索连接字符串,为要运行的位设置标志,然后运行应用程序。You can download the sample, retrieve your connection strings, set the flags for which bits you want to run, and run it. 无需打开代码即可完成这些操作。You can do this without ever opening the code.

下载示例Downloading the sample

  1. 使用以下页面中的 IoT C# 示例:适用于 C# 的 Azure IoT 示例Use the IoT C# samples from this page: Azure IoT Samples for C#. 下载 zip 文件并将其解压缩到计算机。Download the zip file and unzip it on your computer.

  2. 相关代码位于 ./iot-hub/Samples/service/ImportExportDevicesSample 中。The pertinent code is in ./iot-hub/Samples/service/ImportExportDevicesSample. 无需查看或编辑代码即可运行应用程序。You don't need to view or edit the code in order to run the application.

  3. 若要运行应用程序,请指定三个连接字符串和五个选项。To run the application, specify three connection strings and five options. 可以作为命令行参数传入此数据,也可以使用环境变量,或结合使用这两种方法。You pass this data in as command-line arguments or use environment variables, or use a combination of the two. 我们将以命令行参数的形式传递选项,并以环境变量的形式传递连接字符串。We're going to pass the options in as command line arguments, and the connection strings as environment variables.

    原因在于,连接字符串很长很杂乱,且不太可能会更改,但你可能想要更改这些选项并多次运行应用程序。The reason for this is because the connection strings are long and ungainly, and unlikely to change, but you might want to change the options and run the application more than once. 若要更改环境变量的值,必须关闭命令窗口以及所用的 Visual Studio 或 VS Code。To change the value of an environment variable, you have to close the command window and Visual Studio or VS Code, whichever you are using.


下面是运行应用程序时需要指定的五个选项。Here are the five options you specify when you run the application. 稍后我们将在命令行中插入这些选项。We'll put these on the command line in a minute.

  • addDevices(参数 1)-- 若要添加系统生成的虚拟设备,请将此选项设置为 true。addDevices (argument 1) -- set this to true if you want to add virtual devices that are generated for you. 这些设置将添加到源中心。These are added to the source hub. 另外,请设置 numToAdd(参数 2)以指定要添加的设备数。Also, set numToAdd (argument 2) to specify how many devices you want to add. 可注册到一个中心的最大设备数目为 100 万个。此选项旨在用于测试 -- 可以生成特定数目的设备,然后将其复制到另一个中心。The maximum number of devices you can register to a hub is one million.The purpose of this option is for testing -- you can generate a specific number of devices, and then copy them to another hub.

  • copyDevices(参数 3)-- 将此选项设置为 true 会将设备从一个中心复制到另一个中心。copyDevices (argument 3) -- set this to true to copy the devices from one hub to another.

  • deleteSourceDevices(参数 4)-- 将此选项设置为 true 会删除已注册到源中心的所有设备。deleteSourceDevices (argument 4) -- set this to true to delete all of the devices registered to the source hub. 建议等到你已确定所有设备均已转移,再运行此选项。We recommending waiting until you are certain all of the devices have been transferred before you run this. 一旦删除设备,就再也不能将其恢复。Once you delete the devices, you can't get them back.

  • deleteDestDevices(参数 5)-- 将此选项设置为 true 会删除已注册到目标中心(克隆)的所有设备。deleteDestDevices (argument 5) -- set this to true to delete all of the devices registered to the destination hub (the clone). 若要多次复制设备,可能需要执行此操作。You might want to do this if you want to copy the devices more than once.

基本命令是 dotnet run -- 告知 .NET 生成本地 csproj 文件,然后运行该文件。The basic command will be dotnet run -- this tells .NET to build the local csproj file and then run it. 在运行此命令之前,请将命令行参数添加到末尾。You add your command-line arguments to the end before you run it.

命令行类似于以下示例:Your command-line will look like these examples:

    // Format: dotnet run add-devices num-to-add copy-devices delete-source-devices delete-destination-devices

    // Add 1000 devices, don't copy them to the other hub, or delete them. 
    // The first argument is true, numToAdd is 50, and the other arguments are false.
    dotnet run true 1000 false false false 

    // Copy the devices you just added to the other hub; don't delete anything.
    // The first argument is false, numToAdd is 0, copy-devices is true, and the delete arguments are both false
    dotnet run false 0 true false false 

对连接字符串使用环境变量Using environment variables for the connection strings

  1. 若要运行该示例,需要获取新旧 IoT 中心的连接字符串,以及可用于存储临时工作文件的存储帐户的连接字符串。To run the sample, you need the connection strings to the old and new IoT hubs, and to a storage account you can use for temporary work files. 我们将在环境变量中存储这些连接字符串的值。We will store the values for these in environment variables.

  2. 若要获取连接字符串值,请登录到 Azure 门户To get the connection string values, sign in to the Azure portal.

  3. 将连接字符串放到可方便检索它们的某个位置,例如记事本。Put the connection strings somewhere you can retrieve them, such as NotePad. 如果复制以下代码,则可将连接字符串直接粘贴到占位符所在的位置。If you copy the following, you can paste the connection strings in directly where they go. 请不要在等号两边添加空格,否则会改变变量名称。Don't add spaces around the equal sign, or it changes the variable name. 此外,不需要用双引号括住连接字符串。Also, you do not need double-quotes around the connection strings. 如果用引号括住存储帐户连接字符串,该连接字符串会失去作用。If you put quotes around the storage account connection string, it won't work.

    对于 Windows,可按如下示设置环境变量:For Windows, this is how you set the environment variables:

    SET IOTHUB_CONN_STRING=<put connection string to original IoT Hub here>
    SET DEST_IOTHUB_CONN_STRING=<put connection string to destination or clone IoT Hub here>
    SET STORAGE_ACCT_CONN_STRING=<put connection string to the storage account here>

    对于 Linux,可按如下示定义环境变量:For Linux, this is how you define the environment variables:

    export IOTHUB_CONN_STRING="<put connection string to original IoT Hub here>"
    export DEST_IOTHUB_CONN_STRING="<put connection string to destination or clone IoT Hub here>"
    export STORAGE_ACCT_CONN_STRING="<put connection string to the storage account here>"
  4. 对于 IoT 中心连接字符串,请在门户中转到每个中心。For the IoT hub connection strings, go to each hub in the portal. 可以在中心的“资源”中搜索。 You can search in Resources for the hub. 如果你知道某个资源组,可以转到“资源组”,选择该资源组,然后从该资源组的资产列表中选择中心。 If you know the Resource Group, you can go to Resource groups, select your resource group, and then select the hub from the list of assets in that resource group.

  5. 在中心的“设置”中选择“共享访问策略”,然后选择“iothubowner”并复制其中的一个连接字符串。 Select Shared access policies from the Settings for the hub, then select iothubowner and copy one of the connection strings. 对目标中心执行相同的操作。Do the same for the destination hub. 将连接字符串添加到相应的 SET 命令。Add them to the appropriate SET commands.

  6. 对于存储帐户连接字符串,请在“资源”中或其“资源组”下找到并打开该存储帐户。 For the storage account connection string, find the storage account in Resources or under its Resource group and open it.

  7. 在“设置”部分下,选择“访问密钥”并复制其中的一个连接字符串。 Under the Settings section, select Access keys and copy one of the connection strings. 将连接字符串放到包含相应 SET 命令的文本文件中。Put the connection string in your text file for the appropriate SET command.

现在,你已在包含 SET 命令的文件中设置了环境变量,并知道命令行参数有哪些。Now you have the environment variables in a file with the SET commands, and you know what your command-line arguments are. 让我们运行该示例。Let's run the sample.

运行示例应用程序并使用命令行参数Running the sample application and using command-line arguments

  1. 打开命令提示符窗口。Open a command prompt window. 选择“Windows”,然后键入 command prompt 打开命令提示符窗口。Select Windows and type in command prompt to get the command prompt window.

  2. 逐个复制用于设置环境变量的命令,将其粘贴到命令提示符窗口,然后按 Enter。Copy the commands that set the environment variables, one at a time, and paste them into the command prompt window and select Enter. 完成后,在命令提示符窗口中键入 SET 以查看环境变量及其值。When you're finished, type SET in the command prompt window to see your environment variables and their values. 将这些命令复制到命令提示符窗口后,除非打开新的命令提示符窗口,否则不再需要复制。Once you've copied these into the command prompt window, you don't have to copy them again, unless you open a new command prompt window.

  3. 在命令提示符窗口中切换目录,直到进入 ./ImportExportDevicesSample(ImportExportDevicesSample.csproj 文件所在的目录)。In the command prompt window, change directories until you are in ./ImportExportDevicesSample (where the ImportExportDevicesSample.csproj file exists). 然后键入以下命令(包括命令行参数)。Then type the following, and include your command-line arguments.

    // Format: dotnet run add-devices num-to-add copy-devices delete-source-devices delete-destination-devices
    dotnet run arg1 arg2 arg3 arg4 arg5

    dotnet 命令将生成并运行应用程序。The dotnet command builds and runs the application. 由于在运行应用程序时要传入选项,因此每次运行应用程序时都可以更改这些选项的值。Because you are passing in the options when you run the application, you can change the values of them each time you run the application. 例如,你可能想要运行该应用程序一次并创建新设备,然后再次运行该应用程序,并将这些设备复制到新中心,等等。For example, you may want to run it once and create new devices, then run it again and copy those devices to a new hub, and so on. 也可以在同一次运行中执行所有这些步骤,不过,我们建议只在你确定已完成克隆之后,才删除任何设备。You can also perform all the steps in the same run, although we recommend not deleting any devices until you are certain you are finished with the cloning. 下面是创建 1000 个设备,然后将其复制到另一个中心的示例。Here is an example that creates 1000 devices and then copies them to the other hub.

    // Format: dotnet run add-devices num-to-add copy-devices delete-source-devices delete-destination-devices
    // Add 1000 devices, don't copy them to the other hub or delete them. 
    dotnet run true 1000 false false false 
    // Do not add any devices. Copy the ones you just created to the other hub; don't delete anything.
    dotnet run false 0 true false false 

    验证设备已成功复制之后,可以从源中心删除设备,如下所示:After you verify that the devices were copied successfully, you can remove the devices from the source hub like this:

    // Format: dotnet run add-devices num-to-add copy-devices delete-source-devices delete-destination-devices
    // Delete the devices from the source hub.
    dotnet run false 0 false true false 

使用 Visual Studio 运行示例应用程序Running the sample application using Visual Studio

  1. 若要在 Visual Studio 中运行应用程序,请将当前目录切换到 IoTHubServiceSamples.sln 文件所在的文件夹。If you want to run the application in Visual Studio, change your current directory to the folder where the IoTHubServiceSamples.sln file resides. 然后在命令提示符窗口中运行以下命令,在 Visual Studio 中打开解决方案。Then run this command in the command prompt window to open the solution in Visual Studio. 必须在设置环境变量的同一个命令窗口中执行此操作,因此这些变量是已知的。You must do this in the same command window where you set the environment variables, so those variables are known.

  2. 右键单击项目“ImportExportDevicesSample”并选择“设为启动项目”。 Right-click on the project ImportExportDevicesSample and select Set as startup project.

  3. 在 ImportExportDevicesSample 文件夹中 Program.cs 的顶部,设置五个选项的变量。Set the variables at the top of Program.cs in the ImportExportDevicesSample folder for the five options.

    // Add randomly created devices to the source hub.
    private static bool addDevices = true;
    //If you ask to add devices, this will be the number added.
    private static int numToAdd = 0; 
    // Copy the devices from the source hub to the destination hub.
    private static bool copyDevices = false;
    // Delete all of the devices from the source hub. (It uses the IoTHubConnectionString).
    private static bool deleteSourceDevices = false;
    // Delete all of the devices from the destination hub. (Uses the DestIotHubConnectionString).
    private static bool deleteDestDevices = false;
  4. 按 F5 运行应用程序。Select F5 to run the application. 运行完应用程序后,可以查看结果。After it finishes running, you can view the results.

查看结果View the results

可以在 Azure 门户中查看设备,并确认它们是否出现在新位置。You can view the devices in the Azure portal and verify they are in the new location.

  1. 使用 Azure 门户转到新中心。Go to the new hub using the Azure portal. 选择该中心,然后选择“IoT 设备”。 Select your hub, then select IoT Devices. 将会看到刚刚从旧中心复制到克隆的中心的设备。You see the devices you just copied from the old hub to the cloned hub. 还可以查看克隆的中心的属性。You can also view the properties for the cloned hub.

  2. 检查导入/导出错误:在 Azure 门户中转到 Azure 存储帐户,然后查看 ImportErrors.logdevicefiles 容器。Check for import/export errors by going to the Azure storage account in the Azure portal and looking in the devicefiles container for the ImportErrors.log. 如果此文件为空(大小为 0),则表示未发生任何错误。If this file is empty (the size is 0), there were no errors. 如果尝试多次导入同一设备,第二次导入时会拒绝该设备,并将一条错误消息添加到日志文件中。If you try to import the same device more than once, it rejects the device the second time and adds an error message to the log file.

提交更改Committing the changes

此时,你已将中心复制到新位置,并已将设备迁移到新克隆。At this point, you have copied your hub to the new location and migrated the devices to the new clone. 现在需要进行更改,使设备能够与克隆的中心配合工作。Now you need to make changes so the devices work with the cloned hub.

若要提交更改,需要执行以下步骤:To commit the changes, here are the steps you need to perform:

  • 更新每个设备以更改 IoT 中心主机名,将 IoT 中心主机名指向新中心。Update each device to change the IoT Hub host name to point the IoT Hub host name to the new hub. 应使用首次预配设备时所用的相同方法执行此操作。You should do this using the same method you used when you first provisioned the device.

  • 更改引用旧中心的所有应用程序,使其指向新中心。Change any applications you have that refer to the old hub to point to the new hub.

  • 完成后,新中心应会启动并运行。After you're finished, the new hub should be up and running. 旧中心应该没有活动的设备并处于断开连接状态。The old hub should have no active devices and be in a disconnected state.

回滚更改Rolling back the changes

如果你决定回滚更改,请执行以下步骤:If you decide to roll back the changes, here are the steps to perform:

  • 更新每个设备以更改 IoT 中心主机名,将 IoT 中心主机名指向旧中心。Update each device to change the IoT Hub Hostname to point the IoT Hub Hostname for the old hub. 应使用首次预配设备时所用的相同方法执行此操作。You should do this using the same method you used when you first provisioned the device.

  • 更改引用新中心的所有应用程序,使其指向旧中心。Change any applications you have that refer to the new hub to point to the old hub. 例如,如果使用 Azure Analytics,则可能需要重新配置 Azure 流分析输入For example, if you are using Azure Analytics, you may need to reconfigure your Azure Stream Analytics input.

  • 删除新中心。Delete the new hub.

  • 如果你有路由资源,则旧中心上的配置仍应指向正确的路由配置,并且在旧中心重启后,它应该仍可使用这些资源。If you have routing resources, the configuration on the old hub should still point to the correct routing configuration, and should work with those resources after the hub is restarted.

检查结果Checking the results

若要检查结果,请将 IoT 解决方案更改为指向位于新位置的中心,然后运行它。To check the results, change your IoT solution to point to your hub in the new location and run it. 换而言之,请对新中心执行以前对旧中心所执行的相同操作,并确保它们正常工作。In other words, perform the same actions with the new hub that you performed with the previous hub and make sure they work correctly.

如果已实施路由,请测试并确保将消息正确路由到资源。If you have implemented routing, test and make sure your messages are routed to the resources correctly.


在真正确定新中心已启动并运行,并且设备正常工作之前,请不要清理资源。Don't clean up until you are really certain the new hub is up and running and the devices are working correctly. 另外,如果使用路由,请务必对此功能进行测试。Also be sure to test the routing if you are using that feature. 准备就绪后,执行以下步骤来清理旧资源:When you're ready, clean up the old resources by performing these steps:

  • 删除旧中心(如果尚未这样做)。If you haven't already, delete the old hub. 这会从该中心删除所有活动的设备。This removes all of the active devices from the hub.

  • 如果已将路由资源移到新位置,可以删除旧路由资源。If you have routing resources that you moved to the new location, you can delete the old routing resources.

后续步骤Next steps

现已将 IoT 中心连同设备一起克隆到了新区域中的新中心。You have cloned an IoT hub into a new hub in a new region, complete with the devices. 有关对 IoT 中心内的标识注册表执行批量操作的详细信息,请参阅批量导入和导出 IoT 中心设备标识For more information about performing bulk operations against the identity registry in an IoT Hub, see Import and export IoT Hub device identities in bulk.

有关 IoT 中心和中心开发的详细信息,请参阅以下文章。For more information about IoT Hub and development for the hub, please see the following articles.