简体   繁体   English

从 S3 中删除 object 时触发 Lambda function

[英]Trigger Lambda function when object is deleted from S3

I have an SFTP server and Lambda function.我有一个 SFTP 服务器和 Lambda function。 Lambda function is triggered when an object is uploaded to S3 and the object is automatically uploaded to SFTP server via SFTP. Lambda function 是在 object 被上传到 S3 并且 ZA8CFDE6331BD59EB2AC96F8911C4B6 自动上传到 SFTP 服务器时触发的。 (I'm using pysftp) (我正在使用 pysftp)

Is it possible to create a Lambda function that will trigger once the object gets deleted from S3 and to delete it automatically from the server?是否可以创建一个 Lambda function ,一旦 object 从 S3 中删除并从服务器中自动删除它就会触发?

import pysftp,os,boto3

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None

myHostname = os.environ.get('SFTP_HOST')
myUsername = os.environ.get('SFTP_USER')
myPassword = os.environ.get('SFTP_PASS')

s3 = boto3.client("s3")

def lambda_handler(event, context):

    # Get the records for the triggered event
    FILEOBJ = event["Records"][0]
    BUCKET_NAME = str(FILEOBJ['s3']['bucket']['name'])
    KEY = str(FILEOBJ['s3']['object']['key'])
    FILE_NAME = os.path.basename(KEY)
    TMP_FILE_NAME = '/tmp/' +FILE_NAME

    # Download the file/s from the event (extracted above) to the tmp location
    s3.download_file(BUCKET_NAME, KEY, TMP_FILE_NAME)

    with pysftp.Connection(host=myHostname, username=myUsername, password=myPassword, cnopts=cnopts) as sftp:
      with sftp.cd('data/uploads'):
        localFilePath = TMP_FILE_NAME
        sftp.remove(localFilePath)

You can use S3 event with Event type s3:ObjectRemoved:* and trigger Lambda functions.您可以使用事件类型为s3:ObjectRemoved:*的 S3 事件并触发 Lambda 函数。

https://docs.aws.amazon.com/AmazonS3/latest/userguide/notification-how-to-event-types-and-destinations.html https://docs.aws.amazon.com/AmazonS3/latest/userguide/notification-how-to-event-types-and-destinations.html

If you want to use the same function with S3 upload, you can find and use the info in event that Lambda function get like eventName': 'ObjectCreated:Put or eventName': 'ObjectRemoved:Delete .如果您想在 S3 上传时使用相同的 function,您可以在event function get like eventName': 'ObjectCreated:Put eventName': 'ObjectRemoved:Delete

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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