in utils/ci_iot_thing.py [0:0]
def create_iot_thing(thing_name, region, policy_name, certificate_path, key_path, thing_group=None):
""" Create IoT thing along with policy and credentials. """
iot_client = boto3.client('iot', region_name=region)
print(f"Creating thing '{thing_name}'", file=sys.stderr)
iot_client.create_thing(thingName=thing_name)
if thing_group:
iot_client.add_thing_to_thing_group(thingGroupName=thing_group, thingName=thing_name)
try:
print("Creating certificate", file=sys.stderr)
create_cert_response = iot_client.create_keys_and_certificate(
setAsActive=True
)
f = open(certificate_path, "w")
f.write(create_cert_response['certificatePem'])
f.close()
f = open(key_path, "w")
f.write(create_cert_response['keyPair']['PrivateKey'])
f.close()
certificate_arn = create_cert_response['certificateArn']
print("Attaching policy to certificate", file=sys.stderr)
iot_client.attach_policy(policyName=policy_name, target=certificate_arn)
print("Attaching certificate to thing", file=sys.stderr)
iot_client.attach_thing_principal(thingName=thing_name, principal=certificate_arn)
except Exception:
try:
iot_client.delete_thing(thingName=thing_name)
except Exception:
print("ERROR: Could not delete thing", file=sys.stderr)
raise
print("IoT thing created successfully", file=sys.stderr)