def create_thing()

in source/lambda/iot-dr-create-r53-checker/lambda_function.py [0:0]


def create_thing(tmp_dir, timestamp, account_id, region, responseData):
    try:
        thing_name = 'iot-dr-r53-checker-{}'.format(timestamp)
        policy_name = '{}_Policy'.format(thing_name)
        logger.info('thing_name: {} policy_name: {} region: {} account_id: {}'.format(thing_name, policy_name, region, account_id))

        policy_documet = {
              "Version": "2012-10-17",
              "Statement": [
                {
                  "Effect": "Allow",
                  "Action": [
                    "iot:Connect"
                  ],
                  "Resource": "*"
                },
                {
                  "Effect": "Allow",
                  "Action": [
                    "iot:Publish"
                  ],
                  "Resource": [
                    "arn:aws:iot:{}:{}:topic/dr/*".format(region, account_id)
                  ]
                },
                {
                  "Effect": "Allow",
                  "Action": [
                    "iot:Receive"
                  ],
                  "Resource": [
                    "arn:aws:iot:{}:{}:topic/dr/*".format(region, account_id)
                  ]
                },
                {
                  "Effect": "Allow",
                  "Action": [
                    "iot:Subscribe"
                  ],
                  "Resource": [
                    "arn:aws:iot:{}:{}:topicfilter/dr/*".format(region, account_id)
                  ]
                }
              ]
            }

        client = boto3.client('iot')

        response = client.create_policy(
            policyName=policy_name,
            policyDocument=json.dumps(policy_documet)
        )

        response = client.create_keys_and_certificate(setAsActive=True)
        certificate_arn = response['certificateArn']
        certificate_id = response['certificateId']
        logger.info('certificate_arn: {}, certificate_id: {}'.format(certificate_arn, certificate_id))

        cert_file = '{}.cert.pem'.format(thing_name)
        file_c = open('{}/{}'.format(tmp_dir, cert_file),'w')
        file_c.write(response['certificatePem'])
        file_c.close()
        responseData['CERT'] = cert_file

        key_file = '{}.private.key'.format(thing_name)
        file_k = open('{}/{}'.format(tmp_dir, key_file), 'w')
        file_k.write(response['keyPair']['PrivateKey'])
        file_k.close()
        responseData['KEY'] = key_file

        response = client.create_thing(thingName=thing_name)

        response = client.attach_policy(policyName=policy_name,target=certificate_arn)

        response = client.attach_thing_principal(thingName=thing_name, principal=certificate_arn)

    except Exception as e:
        logger.error('{}'.format(e))
        raise Exception(e)