简体   繁体   中英

How to wait for all events in a python lambda handler before sending back a response?

I have an AWS Lambda function in python that uses SSM to run scripts in an EC2 instance. The script after execution creates a folder in S3 (random name). Once the folder gets created, the lambda function needs to return a response with the name of the S3 folder.

When I check the Cloudwatch logs, I can see the name of the folder in one of the events. But the Lambda function returns a 200 before all events have run. How do I make the handler wait till all events are complete before returning the response/200?

import boto3
import time

def lambda_handler(event, context):
     print('event is: ', event)
     if 'number' in event.keys():
        command = 'python lambda_test.py ' + str(event['number']);
        workingDirectory = '/home/ubuntu/src';
        executionTimeout = "3600";
        ssm = boto3.client('ssm');
        ssmresponse = ssm.send_command(InstanceIds=['I-***********a1'], DocumentName='AWSLambdaSampleRun', Parameters= { 'commands': [command], 'workingDirectory': [workingDirectory], 'executionTimeout' : [executionTimeout] }, ServiceRoleArn='arn:aws-us-west-1:sts::***************:assumed-role/lambda/sample', OutputS3BucketName = 'sample-ui' )
     records = [x for x in event.get('Records', []) if x.get('eventName') == 'ObjectCreated:Put']
     print("records : ", records)
     if records:
        awsRegion = records[0].get('awsRegion', '')
        info = records[0].get('s3', {})
        file_key = info.get('object', {}).get('key')
        bucket_name = info.get('bucket', {}).get('name')
        message = {
        'body' : "Script execution completed. See https://console.amazonaws.com/s3/buckets/" + bucket_name + "/" + file_key.replace('err', 'out') + "/?region=" + awsRegion + "&tab=overview  for complete output"
        }
        print message
        return message

An earlier event has the parameter ('event is: ', {u'number': u'1'})

Post script execution, the event holds the name of the s3 key -

('event is: ', {u'Records': [{u'eventVersion': u'2.1', u'eventTime': u'2019-04-15T04:48:06.217Z', u'requestParameters': {u'sourceIPAddress': u'**.**.**.***'}, u's3': {u'configurationId': u'*************', u'object': {u'eTag': u'*********8a11', u'sequencer': u'*********83C', u'key': u'**********', u'size': 5946}, u'bucket': {u'arn': u'arn:aws-us-****', u'name': u'sample', u'ownerIdentity': {u'principalId': u'AWS:********'}}, u's3SchemaVersion': u'1.0'}, u'responseElements': {u'x-amz-id-2': u'**/**/**/**=', u'x-amz-request-id': u'***'}, u'awsRegion': u'us-west-1', u'eventName': u'ObjectCreated:Put', u'userIdentity': {u'principalId': u'AWS:**:I-**'}, u'eventSource': u'aws:s3'}]})

https://pypi.org/project/waiting/

Check this out. I ran into a similar situation recently where I was testing an event driven lambda.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM