def handler(event, context):
    # make sure we send a failure to CloudFormation if the function
    # is going to timeout
    print("EVENT: " + str(event))
    timer = threading.Timer(
        (context.get_remaining_time_in_millis() / 1000.00) - 0.5,
        timeout,
        args=[event, context])
    timer.start()
    print('Received event: %s' % json.dumps(event))
    status = sendcfnresponse.SUCCESS
    responseData = {}
    config = event['ResourceProperties']
    try:
        if event['RequestType'] in ['Create', 'Update']:
            if config['Resource'] == 'CopyConnectorLambdaZip' or config[
                    'Resource'] == 'CopySLMPConnectorLambdaZip':
                print("Config: {}".format(str(config)))
                source_bucket = config['SourceBucket']
                dest_bucket = config['DestBucket']
                prefix = config['SourcePrefix']
                dest_prefix = config['DestPrefix']
                objects = config['Objects']
                responseData['UUID'] = str(uuid.uuid4())
                responseData['Data'] = copy_objects(source_bucket, dest_bucket,
                                                    prefix, objects,
                                                    dest_prefix)
            elif config['Resource'] == 'SendAnonymousMetrics':
                if event['RequestType'] == 'Create':
                    config['EventType'] = 'DeployStack'
                elif event['RequestType'] == 'Update':
                    config['EventType'] = 'UpdateStack'
                try:
                    send_metrics(config)
                except:
                    pass
        elif event['RequestType'] == 'Delete':
            if config['Resource'] == 'CopyConnectorLambdaZip' or config[
                    'Resource'] == 'CopySLMPConnectorLambdaZip':
                dest_bucket = config['DestBucket']
                dest_prefix = config['DestPrefix']
                objects = config['Objects']
                responseData['Data'] = delete_objects(dest_bucket, dest_prefix,
                                                      objects)
            elif config['Resource'] == 'SendAnonymousMetrics':
                delete_config = event['ResourceProperties']
                delete_config['EventType'] = 'DeleteStack'
                send_metrics(delete_config)
    except Exception as e:
        logging.error('Exception: %s' % e, exc_info=True)
        status = sendcfnresponse.FAILED
    finally:
        timer.cancel()
        sendcfnresponse.send_response(event, context, status, responseData)
Пример #2
0
def handler(event, context):
    # make sure we send a failure to CloudFormation if the function
    # is going to timeout
    timer = threading.Timer(
        (context.get_remaining_time_in_millis() / 1000.00) - 0.5,
        timeout,
        args=[event, context])
    timer.start()
    logger.info('Received event: %s', json.dumps(event))
    status = sendcfnresponse.SUCCESS
    responseData = {}
    config = event['ResourceProperties']

    try:
        if event['RequestType'] in ['Create', 'Update']:
            if config['Resource'] == 'CreateUUID':
                responseData['UUID'] = str(uuid.uuid4())
            elif config['Resource'] == 'SendAnonymousMetrics':
                if event['RequestType'] == 'Create':
                    config['EventType'] = 'DeployStack'
                elif event['RequestType'] == 'Update':
                    config['EventType'] = 'UpdateStack'

                try:
                    send_metrics(config)
                except:
                    pass
        elif event['RequestType'] == 'Delete':
            if config['Resource'] == 'SendAnonymousMetrics':
                config['EventType'] = 'DeleteStack'

                try:
                    send_metrics(config)
                except:
                    pass
    except Exception as e:
        logging.error('Exception: %s' % e, exc_info=True)
        status = sendcfnresponse.FAILED
    finally:
        timer.cancel()
        sendcfnresponse.send_response(event, context, status, responseData)
def handler(event, context):
    try:
        logger.info('Received event: {}'.format(json.dumps(event)))
        resource = event['ResourceProperties']['Resource']

        if resource == 'CreateGGCertAndKeys':
            if event['RequestType'] == 'Create':
                iot_end_point = iot_client.describe_endpoint(endpointType='iot:Data-ATS')['endpointAddress']
                cert_id, cert_arn, cert_pem, private_key, public_key = generate_cert_and_keys(event)
                logger.info('Created cert: %s ' % (cert_id))

                filePrefix = cert_id[0:7]
                cert_file_name = filePrefix + "-cert.pem"
                private_key_name = filePrefix + "-private.key"
                public_key_name = filePrefix + "-public.key"
                certs_dir = '/tmp/certs/'

                write_file(cert_file_name, certs_dir, cert_pem)
                write_file(private_key_name, certs_dir, private_key)
                write_file(public_key_name, certs_dir, public_key)
                get_amazon_ca(event)

                config_file_name, config_file_dir, data = create_config_json(cert_file_name, private_key_name, iot_end_point)
                write_file(config_file_name, config_file_dir, json.dumps(data))

                setup = create_setup_script(event)
                tar_file = create_tar_archive(certs_dir, config_file_dir, setup)
                logger.info("TarFile: {}".format(tar_file))
                generated_s3_url = write_tar_to_s3(tar_file)

                response_data['certificateId'] = cert_id
                response_data['certificateArn'] = cert_arn
                response_data['certificateName'] = cert_file_name
                response_data['privateKeyName'] = private_key_name
                response_data['publicKeyName'] = public_key_name
                response_data['iotEndpoint'] = iot_end_point
                response_data['generatedS3URL'] = generated_s3_url
        elif resource == 'DeleteGGCertAndKeys':
            if event['RequestType'] == 'Delete':
                cert_id = event['ResourceProperties']['CertId']
                greengrass_group_id = event['ResourceProperties']['GreengrassGroupId']

                logger.info('Resetting the Greengrass group')
                greengrass_client.reset_deployments(
                    GroupId=greengrass_group_id,
                    Force=True
                )

                logger.info('Checking thing principals')
                try:
                    response = iot_client.list_thing_principals(thingName=THING_NAME)
                    while response['principals']:
                        logger.info('Checking thing principals again...')
                        time.sleep(3)
                        response = iot_client.list_thing_principals(thingName=THING_NAME)
                except iot_client.exceptions.ResourceNotFoundException as error:
                    logger.error("There was an error deleteing Greengrass resources: {}".format(error))
                    pass
                else:
                    logger.info('Deleting cert: %s', cert_id)
                    iot_client.update_certificate(
                        certificateId=cert_id,
                        newStatus='INACTIVE'
                    )
                    iot_client.delete_certificate(
                        certificateId=cert_id,
                        forceDelete=True
                    )

        status = sendcfnresponse.SUCCESS
    except Exception as e:
        logger.error('Error: {}'.format(e))
        status = sendcfnresponse.FAILED

    logger.info('Returning response of: {}, with result of: {}'.format(status, response_data))
    sendcfnresponse.send_response(event, context, status, response_data)
def timeout(event, context):
    logging.error(
        'Execution is about to time out, sending failure response to CloudFormation'
    )
    sendcfnresponse.send_response(event, context, sendcfnresponse.FAILED, {})