AWS CDK - add an s3 trigger to invoke a lambda

Viewed 5880
1 Answers

if you want to trigger a lambda after a file was uploaded to S3 you have two ways:

S3 Eventnotifications:

this is a S3 specific feature and supports lambda as a target and also SQS and SNS. You can find more info here: https://docs.aws.amazon.com/AmazonS3/latest/dev/NotificationHowTo.html

CloudTrail:

CloudTrail logs pretty much all Events in your account and you can react to them if you want.

  1. create a bucket
  2. Create a trail, you might want to select write only, to reduce the amount of stuff that gets written
  3. add the bucket to the trail with addS3EventSelector
  4. add your target
        uploadBucket.onCloudTrailWriteObject('cwEvent', {
            target: new targets.LambdaFunction()
        })

this will create a CloudWatch Event.

On the first step you might need to also log it to cloud watch logs, I'm not sure anymore:

        const trail = new cloudtrail.Trail(this, 'CloudTrail', {
            sendToCloudWatchLogs: true,
            managementEvents: cloudtrail.ReadWriteType.WRITE_ONLY,
        });

I prefer version two, because CloudWatch Event supports way more targets than SQS, SNS and Lambda. I used it to trigger a Step Function for example.

Docs: https://docs.aws.amazon.com/cdk/api/latest/docs/aws-cloudtrail-readme.html https://docs.aws.amazon.com/cdk/api/latest/docs/aws-s3-readme.html#bucket-notifications

Related