def setup_agent()

in setup/lambda-custom-resource/prepare_dev_package_cr.py [0:0]


def setup_agent(thing_group_name, thing_group_arn):
    """Creates configuration file and sets up SageMaker Edge Agent for deployment
    onto a Amazon S3 bucket. Registers a device with a device fleet, creates IoT
    certificates and attaches them to the previously created IoT thing. Saves 
    certificates onto local disk to make it ready for uploading to S3.

    Args:
        thing_group_name (string): a name for the IoT thing group
        thing_group_arn (string): the ARN of the IoT thing group
    """

    local_base_path = LOCAL_DIR_PREFIX + "agent/certificates/iot/edge_device_cert_%s.pem"
    relative_base_path = "agent/certificates/iot/edge_device_cert_%s.pem"
    thing_arn_template = thing_group_arn.replace('thinggroup', 'thing').replace(thing_group_name, '%s')
    cred_host = iot_client.describe_endpoint(endpointType='iot:CredentialProvider')['endpointAddress']

    # Check length of device name string
    if len(sm_edge_device_name) > 64:
        LOGGER.error("Device name for edge device is too long. Needs to be <64 characters.")
        raise ClientError('Device name for edge device is longer than 64 characters. Please choose a shorter value for ProjectName.')

    # register the device in the fleet    
    # the device name needs to have 36 chars
    dev = [{'DeviceName': sm_edge_device_name, 'IotThingName': iot_thing_name}]    
    try:        
        sm_client.describe_device(DeviceFleetName=sm_em_fleet_name, DeviceName=sm_edge_device_name)
        LOGGER.info("Device was already registered on SageMaker Edge Manager")
    except ClientError as e:
        if e.response['Error']['Code'] != 'ValidationException': raise e
        LOGGER.info("Registering a new device %s on fleet %s" % (sm_edge_device_name, sm_em_fleet_name))
        sm_client.register_devices(DeviceFleetName=sm_em_fleet_name, Devices=dev)
        iot_client.add_thing_to_thing_group(
            thingGroupName=thing_group_name,
            thingGroupArn=thing_group_arn,
            thingName=iot_thing_name,
            thingArn=thing_arn_template % iot_thing_name
        )        
    
    # if you reach this point you need to create new certificates
    # generate the certificates    
    cert = local_base_path % ('cert')
    key = local_base_path % ('pub')
    pub = local_base_path % ('key')

    # Relative paths needed for setting path in config file
    cert_relative = relative_base_path % ('cert')
    key_relative = relative_base_path % ('pub')
    pub_relative = relative_base_path % ('key')
    
    cert_meta=iot_client.create_keys_and_certificate(setAsActive=True)
    cert_arn = cert_meta['certificateArn']
    with open(cert, 'w') as c: c.write(cert_meta['certificatePem'])
    with open(key,  'w') as c: c.write(cert_meta['keyPair']['PrivateKey'])
    with open(pub,  'w') as c: c.write(cert_meta['keyPair']['PublicKey'])
        
    # attach the certificates to the policy and to the thing
    iot_client.attach_policy(policyName=iot_policy_name, target=cert_arn)
    iot_client.attach_thing_principal(thingName=iot_thing_name, principal=cert_arn)        
    
    LOGGER.info("Creating agent config JSON file")

    # Please note that the $WORKDIR variables need to be replaced by the absolute path of the working directory of your project.
    # If you follow the guide, the install script will automatically replace those.
    agent_params = {
        "sagemaker_edge_core_device_name": sm_edge_device_name,
        "sagemaker_edge_core_device_fleet_name": sm_em_fleet_name,
        "sagemaker_edge_core_region": AWS_REGION,
        "sagemaker_edge_provider_provider": "Aws",
        "sagemaker_edge_provider_provider_path" : "$WORKDIR/agent/lib/libprovider_aws.so",
        "sagemaker_edge_core_root_certs_path": "$WORKDIR/agent/certificates/root",
        "sagemaker_edge_provider_aws_ca_cert_file": "$WORKDIR/agent/certificates/iot/AmazonRootCA1.pem",
        "sagemaker_edge_provider_aws_cert_file": "$WORKDIR/%s" % cert_relative,
        "sagemaker_edge_provider_aws_cert_pk_file": "$WORKDIR/%s" % key_relative,
        "sagemaker_edge_provider_aws_iot_cred_endpoint": "https://%s/role-aliases/%s/credentials" % (cred_host,role_alias),
        "sagemaker_edge_core_capture_data_destination": "Cloud",
        "sagemaker_edge_provider_s3_bucket_name": BUCKET_NAME,
        "sagemaker_edge_core_folder_prefix": "edge-agent-inference-data-capture",
        "sagemaker_edge_core_capture_data_buffer_size": 30,
        "sagemaker_edge_core_capture_data_batch_size": 10,
        "sagemaker_edge_core_capture_data_push_period_seconds": 10,
        "sagemaker_edge_core_capture_data_base64_embed_limit": 2,
        "sagemaker_edge_log_verbose": False
    }
    with open(LOCAL_DIR_PREFIX + 'agent/conf/config_edge_device.json', 'w') as conf:
        conf.write(json.dumps(agent_params, indent=4))