I am having this problem in CDK. I have a lambda triggered by a SNS Topic (receiving events from a S3 bucket) but right now its executing on every single message being delivered to the SNS Topic. I want the Lambda to only execute on specific bucket name, file ending and PutObject operations.
I know how to connect SNS to my lambda, just not with the filter:
const myTopic = new sns.Topic(this, "Topic", {});
myTopic.addToResourcePolicy(new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["sns:Publish"],
resources: [myTopic.topicArn],
principals: [new iam.AccountPrincipal('XXXXXXXXX')]
}))
const snsEventSource = new lambdaEventSources.SnsEventSource(myTopic);
myLambda.addEventSource(snsEventSource)
I am not sure how to add the filter, I have tried playing around with sns.SubscriptionFilter without any luck
I got it to work with code like this:
const myTopic = new sns.Topic(this, "Topic", {});
myTopic.addToResourcePolicy(new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["sns:Publish"],
resources: [myTopic.topicArn],
principals: [new iam.AccountPrincipal('XXXXXXXXX')]
}))
myLambda.grantInvoke(new iam.ServicePrincipal('sns.amazonaws.com'))
myTopic.addSubscription(new subs.LambdaSubscription(myLambda, {
filterPolicy: {
S3_BUCKET_NAME: sns.SubscriptionFilter.stringFilter({allowlist: ['myBucket']}),
S3_EVENT_NAME: sns.SubscriptionFilter.stringFilter({allowlist: ['ObjectCreated:Put']})
}
}))