How to know which s3 bucket invokes the lambda in a cdk app?


Say I have a CDK app deploying the S3 -> EventBridege -> Lambda stack, and there are many s3 buckets that will invoke the same lambda. The lambda handler runs a program differetly based on the source bucket.

Normally, we can read the bucket name from the incoming event to know which bucket invokes the lambda, but since the bucket name might be different each time a new deployment is made, depending on the bucket name seems not reliable.

So, is there a better way to know what the bucket is invoking the lambda in the lambda handler code?

3 Answers
Accepted Answer

If I understand correctly, you deploy multiple stacks, each with a different bucket, but all with the same Lambda function. You want the bucket name to be determined by CFN, but you need to know in the function the origin bucket, or more specifically, what the bucket is used for, not its name.

If this is the case and your function performs different actions based on the origin bucket, I would recommend creating different functions. This way each stack creates a different S3 bucket with a different function, that knows what to do.

profile picture
answered 4 months ago

Hi, while creating an S3 bucket using CDK you can manually set the bucketName property:

This will ensure that the bucket has the same name every-time it is deployed, which should address your issue.



answered 4 months ago

Fair enough! In that case, your best bet is probably to using S3 to publish event messages to SNS which would in-turn trigger your Lambda function: Specifically, configuring each bucket to send SNS events with a different SNS Topic would allow your Lambda function to determine where the event came from.

answered 4 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions