

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 注册并验证您的设备实例集
<a name="edge-getting-started-step3"></a>

在本节中，您将创建您的 AWS IoT 事物对象，创建设备队列，注册您的设备队列以使其能够与云交互，创建 X.509 证书以对您的设备进行身份验证，将角色别名与 AWS IoT 创建队列时生成的角色别名关联，为凭证提供者获取 AWS 账户特定的终端节点，获取官方的 Amazon 根 CA 文件，并将亚马逊 CA 文件上传到 Amazon S3。 AWS IoT Core

1. **创造 AWS IoT 东西。**

   SageMaker Edge Manager 利用这些 AWS IoT Core 服务来促进边缘设备和 AWS 云端点之间的连接。将设备设置为与 Edge Manager 配合使用后，您可以利用现有 AWS IoT 功能。

   要将设备连接到 AWS IoT，您需要创建 AWS IoT *事物对象*、创建客户端证书并将其注册到 AWS 物联网，以及为设备创建和配置 IAM 角色。

   首先，使用您之前使用 Boto3 创建的 AWS IoT 客户端 (`iot_client`) 创建 AWS IoT 事物对象。以下示例显示了如何创建两个事物对象：

   ```
   iot_thing_name = 'sample-device'
   iot_thing_type = 'getting-started-demo'
   
   iot_client.create_thing_type(
       thingTypeName=iot_thing_type
   )
   
   # Create an AWS IoT thing objects
   iot_client.create_thing(
       thingName=iot_thing_name,
       thingTypeName=iot_thing_type
   )
   ```

1. **创建您的设备队列。**

   使用上一步中定义的 A SageMaker I 客户端对象创建设备队列。您还可以使用 SageMaker AI 控制台创建设备队列。

   ```
   import time
   device_fleet_name="demo-device-fleet" + str(time.time()).split('.')[0]
   device_name="sagemaker-edge-demo-device" + str(time.time()).split('.')[0]
   ```

   指定您的 IoT 角色 ARN。这允许 AWS IoT 向设备授予临时证书。

   ```
   device_model_directory='device_output'
   s3_device_fleet_output = 's3://{}/{}'.format(bucket, device_model_directory)
   
   sagemaker_client.create_device_fleet(
       DeviceFleetName=device_fleet_name,
       RoleArn=iot_role_arn, # IoT Role ARN specified in previous step
       OutputConfig={
           'S3OutputLocation': s3_device_fleet_output
       }
   )
   ```

    AWS IoT 角色别名是在创建设备队列时创建的。此角色别名与在后面的步骤中 AWS IoT 使用该`iot_client`对象相关联。

1. **注册您的设备队列。**

   要与云端交互，您需要在 SageMaker 边缘管理器中注册您的设备。在此示例中，您在已创建的队列中注册单个设备。要注册设备，您需要提供设备名称和 AWS IoT 事物名称，如以下示例所示：

   ```
   # Device name should be 36 characters
   device_name = "sagemaker-edge-demo-device" + str(time.time()).split('.')[0]
   
   sagemaker_client.register_devices(
       DeviceFleetName=device_fleet_name,
       Devices=[
           {
               "DeviceName": device_name,
               "IotThingName": iot_thing_name
           }
       ]
   )
   ```

1. **创建 X.509 证书。**

   创建 AWS IoT 事物对象后，必须为事物对象创建 X.509 设备证书。此证书用于向 AWS IoT Core验证设备身份。

   使用以下命令使用之前定义的 AWS IoT 客户端 (`iot_client`) 创建私钥、公钥和 X.509 证书文件。

   ```
   # Creates a 2048-bit RSA key pair and issues an X.509 # certificate 
   # using the issued public key.
   create_cert = iot_client.create_keys_and_certificate(
       setAsActive=True 
   )
   
   # Get certificate from dictionary object and save in its own
   with open('./device.pem.crt', 'w') as f:
       for line in create_cert['certificatePem'].split('\n'):
           f.write(line)
           f.write('\n')
   # Get private key from dictionary object and save in its own 
   with open('./private.pem.key', 'w') as f:
       for line in create_cert['keyPair']['PrivateKey'].split('\n'):
           f.write(line)
           f.write('\n')
   # Get a private key from dictionary object and save in its own 
   with open('./public.pem.key', 'w') as f:
       for line in create_cert['keyPair']['PublicKey'].split('\n'):
           f.write(line)
           f.write('\n')
   ```

1. **将角色别名与关联 AWS IoT。**

   使用 SageMaker AI (`sagemaker_client.create_device_fleet()`) 创建设备队列时，系统会为您生成角色别名。 AWS IoT 角色别名为连接的设备提供了一种 AWS IoT 使用 X.509 证书进行身份验证的机制，然后从与角色别名关联的 IAM 角色获取短期 AWS 证书。 AWS IoT 使用角色别名，您可以更改角色，无需更新设备。使用 `DescribeDeviceFleet` 获取角色别名和 ARN。

   ```
   # Print Amazon Resource Name (ARN) and alias that has access 
   # to AWS Internet of Things (IoT).
   sagemaker_client.describe_device_fleet(DeviceFleetName=device_fleet_name)
   
   # Store iot role alias string in a variable
   # Grabs role ARN
   full_role_alias_name = sagemaker_client.describe_device_fleet(DeviceFleetName=device_fleet_name)['IotRoleAlias']
   start_index = full_role_alias_name.find('SageMaker') # Find beginning of role name  
   role_alias_name = full_role_alias_name[start_index:]
   ```

   使用`iot_client`可以方便地将创建设备队列时生成的角色别名与 AWS IoT以下角色相关联：

   ```
   role_alias = iot_client.describe_role_alias(
                       roleAlias=role_alias_name)
   ```

   有关 IAM 角色别名的更多信息，请参阅[角色别名允许访问未使用的服务](https://docs.aws.amazon.com/iot/latest/developerguide/audit-chk-role-alias-unused-svcs.html)。

   您 AWS IoT 之前创建并注册了证书，以便成功对设备进行身份验证。现在，您需要创建策略并将其附加到证书，以授权对安全令牌的请求。

   ```
   alias_policy = {
     "Version": "2012-10-17",		 	 	 
     "Statement": {
       "Effect": "Allow",
       "Action": "iot:AssumeRoleWithCertificate",
       "Resource": role_alias['roleAliasDescription']['roleAliasArn']
     }
   }
   
   policy_name = 'aliaspolicy-'+ str(time.time()).split('.')[0]
   aliaspolicy = iot_client.create_policy(policyName=policy_name,
                                          policyDocument=json.dumps(alias_policy))
   
   # Attach policy
   iot_client.attach_policy(policyName=policy_name,
                               target=create_cert['certificateArn'])
   ```

1. **获取凭证提供商的 AWS 账户专用端点。**

   边缘设备需要端点才能代入凭证。获取凭证提供程序的 AWS 账户特定端点。

   ```
   # Get the unique endpoint specific to your AWS account that is making the call.
   iot_endpoint = iot_client.describe_endpoint(
       endpointType='iot:CredentialProvider'
   )
   
   endpoint="https://{}/role-aliases/{}/credentials".format(iot_endpoint['endpointAddress'],role_alias_name)
   ```

1. **获取官方的 Amazon 根 CA 文件并将其上传到 Amazon S3 存储桶。**

   在 Jupyter 笔记本中使用以下内容或 AWS CLI （如果您使用终端，请删除 '\!' 魔法函数）：

   ```
   !wget https://www.amazontrust.com/repository/AmazonRootCA1.pem
   ```

   使用端点向凭证提供程序发出 HTTPS 请求以返回安全令牌。以下示例命令使用 `curl`，但您可以使用任何 HTTP 客户端。

   ```
   !curl --cert device.pem.crt --key private.pem.key --cacert AmazonRootCA1.pem $endpoint
   ```

   如果证书已通过验证，请将密钥和证书上传到您的 Amazon S3 存储桶 URI：

   ```
   !aws s3 cp private.pem.key s3://{bucket}/authorization-files/
   !aws s3 cp device.pem.crt s3://{bucket}/authorization-files/
   !aws s3 cp AmazonRootCA1.pem s3://{bucket}/authorization-files/
   ```

   通过将密钥和证书移至其他目录来清理工作目录：

   ```
   # Optional - Clean up working directory
   !mkdir authorization-files
   !mv private.pem.key device.pem.crt AmazonRootCA1.pem authorization-files/
   ```