in cross-account-register-ztp/python/lambda/lambda_function.py [0:0]
def lambda_handler(event, context):
global client
region = 'us-east-1' #default
certificatePEM = ""
attribute_1 = "undefined"
body = json.loads(event['body'])
if 'region' in body.keys():
region=body['region']
if 'certificate' in body.keys():
certificatePEM = body['certificate']
if thing_attribute_name in body.keys():
attribute_1 = body[thing_attribute_name]
client = boto3.client('iot', region_name=region)
if not verify_certificate(certificatePEM):
return {
'statusCode': 400,
'body': json.dumps('Failed to verify certificate.')
}
try:
response = client.register_certificate_without_ca(
certificatePem=certificatePEM,
status='ACTIVE'
)
except Exception as e:
return {
'statusCode': 400,
'body': json.dumps('Failed to register certificate: {}'.format(e))
}
certificateArn = response['certificateArn']
certificateId = response['certificateId']
try:
response = client.create_thing(
thingName = certificateId,
attributePayload={
'attributes': {
thing_attribute_name : attribute_1
},
'merge': True
}
)
except Exception as e:
print ('Failed to Create Thing')
cleanup_resources(certificateArn, certificateId)
return {
'statusCode': 400,
'body': json.dumps('Failed to create thing: {}'.format(e))
}
thingName = response['thingName']
thingArn = response['thingArn']
try:
response = client.attach_principal_policy(
policyName=managed_iot_policy,
principal=certificateArn
)
except Exception as e:
print ('Failed to attach policy to certificate')
cleanup_resources(certificateArn, certificateId, thingName)
return {
'statusCode': 400,
'body': json.dumps('Failed to attach policy to cert: {}'.format(e))
}
try:
response = client.attach_thing_principal(
thingName=thingName,
principal=certificateArn
)
except Exception as e:
print ('Failed to attach certificate to Thing')
cleanup_resources(certificateArn, certificateId, thingName)
return {
'statusCode': 400,
'body': json.dumps('Failed to attach cert to thing: {}'.format(e))
}
response = client.describe_endpoint(
endpointType='iot:Data-ATS'
)
endpointAddress = {
'endpointAddress': response['endpointAddress']
}
print ('Successfully created thing, registered certificate.')
return {
'statusCode': 200,
'body': json.dumps(endpointAddress)
}