Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AWS CDK - add an s3 trigger to invoke a lambda

I'm trying to build a lambda function with s3 trigger throw the CDK deployment, does somebody knows if it possible to programmatically trigger the CDK code?

I found those links:

  1. Lookup S3 Bucket and add a trigger to invoke a lambda
  2. With CDK, can it be triggered through a lambda to deploy the stack

but they were a few months ago and I wanted to know if anything was renewed

like image 487
gil cohen Avatar asked Nov 23 '25 10:11

gil cohen


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

like image 98
Jonny Rimek Avatar answered Nov 24 '25 23:11

Jonny Rimek



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!