如何在发送响应之前等待python lambda处理程序中的所有事件?

2024-05-08 19:33:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我在python中有一个AWS Lambda函数,它使用SSM在EC2实例中运行脚本。执行后的脚本在S3(随机名称)中创建一个文件夹。创建文件夹后,lambda函数需要返回一个带有S3文件夹名称的响应。在

当我检查Cloudwatch日志时,我可以在其中一个事件中看到文件夹的名称。但是Lambda函数在所有事件运行之前返回200。在返回响应/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

早期事件具有参数('event is : ', {u'number': u'1'})

脚本执行后,事件保存s3键的名称-

{cd2}


Tags: lambda函数脚本文件夹名称eventnumberget