aws-cdk icon indicating copy to clipboard operation
aws-cdk copied to clipboard

s3: allow defining bucket notifications for unowned buckets

Open amirsch opened this issue 7 years ago • 79 comments

The use case is fairly simple, creating a new lambda function and attaching an event source from an existing S3 bucket of object creation.

following example code:

   const exampleBucket = Bucket.import(this, 'example-bucket', {bucketArn: 'arn:aws:s3:::example-bucket-arn'});
   fn.addEventSource(new S3EventSource(exampleBucket, { events: [EventType.ObjectCreated] }));

This code has a type mismatch (ImportedBucket vs Bucket), and doesn't work regardless. Is there another way to use an existing bucket for an S3 event source?

Additional 2x👍 from duplicated issues

amirsch avatar Mar 12 '19 12:03 amirsch

I have the same problem too. It looks like the IBucket interface isn't an extension of the Bucket interface, and doesn't have the onEvent() function. I found instead the onPutObject() function which is kind of suitable for my intent, but it isn't as general as onEvent().

Is this difference intended? Am I missing something?

Thanks in advance for the clarification.

simonemazzoni avatar Mar 22 '19 13:03 simonemazzoni

Due to current limitations with CloudFormation and the way we implemented bucket notifications in the CDK, it is impossible to add bucket notifications on an imported bucket. This is why the event source uses s3.Bucket instead of s3.IBucket.

You could use onPutObject:

const bucket = s3.Bucket.import(this, 'B', {
  bucketName: 'my-bucket'
});

const fn = new lambda.Function(this, 'F', {
  code: lambda.Code.inline('boom'),
  runtime: lambda.Runtime.NodeJS810,
  handler: 'index.handler'
});

bucket.onPutObject('put-object', fn);

eladb avatar Apr 04 '19 14:04 eladb

We can vend another lambda event source which will be more limited in capabilities and will use putObject. Maybe something like S3PutObjectEventSource

eladb avatar Apr 04 '19 14:04 eladb

@eladb

You could use onPutObject:

sure I can, but what if I want to bind the lambda to other bucket events?

Below are the events you can choose from the console, and the checked option is my choice. I cannot do the same thing from the cdk apparently. Screen Shot 2019-04-04 at 16 45 27

Am I correct?

simonemazzoni avatar Apr 04 '19 14:04 simonemazzoni

Sadly no, and neither from CloudFormation.

eladb avatar Apr 04 '19 14:04 eladb

Oh, I see. Should we point this out to AWS directly then?

simonemazzoni avatar Apr 04 '19 15:04 simonemazzoni

Hi, I'm facing the same problem. Is there any news so far or is the issue planned to be fixed soon?

If I'm understanding correctly what @eladb proposes, it implies a different event notification flow:

  • The first one, which is the one that I need, comes from an event source notification and its reflected as an event setting bucket.
  • The approach from @eladb comes from a cloud trail event and its reflected as an object-level logging adding additional costs to the pipeline.

Is there no way to add an event source to a lambda function from an existing bucket using the aws cdk and without using cloud trail?

This is my use case example using serverless framework and what I'm trying to replicate using the cdk:

plugins:
  - serverless-plugin-existing-s3

functions:
  <function-name>:
    handler: handler.main
    events:
      - existingS3:
          bucket: <bucket-name>
          events:
            - s3:ObjectCreated:*
          rules:
            - Suffix: .foo

nebur395 avatar Jun 27 '19 10:06 nebur395

aws-cdk.aws-s3.Bucket.onPutObject appears to no longer exist. on_cloud_trail_put_object looks like the closest alternative, but that requires creating a CloudTrail trail to capture the event first. Is that the best way to do this now?

TomDufall avatar Jun 28 '19 13:06 TomDufall

Bucket.add_event_notification seems to have replaced Bucket.add_event_source. Updated minimal example that works with a Bucket but not an IBucket below.

my_bucket.add_event_notification(
    aws_s3.EventType.OBJECT_CREATED,
    aws_s3_notifications.LambdaDestination(my_lambda),
    )

TomDufall avatar Jun 28 '19 15:06 TomDufall

@eladb Is there further updates on this, we have many use cases to put notifications on existing buckets. According the below ticket, it says it is implemented in Serverless, any plans to extend this too CDK.

Add support for existing S3 buckets #6290 https://github.com/serverless/serverless/pull/6290

dandu1008 avatar Jul 31 '19 16:07 dandu1008

+1 @dandu1008 @eladb

It is already implemented in Serverless Framework. We also have a lot of use cases that consist on adding lambda notifications on existing buckets.

Anyway it seems is not a problem related only with existing buckets, but with existing resources. We've tried the same approach but trying to subscribe a lambda to an existing SNS topic instead of an existing bucket (this is also possible using Serverless Framework) and it ends in the same result. You cannot add it because importing an existing SNS topic (using fromTopicArn()) returns an ITopic and addEventSource() expects only a Topic.

It is important for us, and in my opinion it's not an uncommon use case, please, it would be great to have that implementation.

Any feedback from your side would be pleasantly appreciated to know that this ticket has not been forgotten.

Best Regards

nebur395 avatar Aug 02 '19 12:08 nebur395

@nebur395 -- looking at the Serverless link you sent, you could approach the problem in a similar method using this experimental package. Obviously experimental, but perhaps your feedback and PR if you find something that is robust and community needed?

moofish32 avatar Aug 13 '19 04:08 moofish32

Due to current limitations with CloudFormation and the way we implemented bucket notifications in the CDK, it is impossible to add bucket notifications on an imported bucket. This is why the event source uses s3.Bucket instead of s3.IBucket.

You could use onPutObject:

const bucket = s3.Bucket.import(this, 'B', {
  bucketName: 'my-bucket'
});

const fn = new lambda.Function(this, 'F', {
  code: lambda.Code.inline('boom'),
  runtime: lambda.Runtime.NodeJS810,
  handler: 'index.handler'
});

bucket.onPutObject('put-object', fn);

Fundamentally this problem stems from the way the cloudformation team designed the S3 bucket resource. They chose to put the notifications as a property of the bucket itself rather than as a separate resource.

This choice has always baffled me and it results in the inability to do anything with an existing S3 bucket other than set the S3 bucket policy (which is a separate resource in cloudformation).

Until such time as this changes (which is probably never) CDK will not be able to implement notifications on existing buckets without using Custom Resources. This is because CDK is ultimately just producing a cloudformation template. I am hopeful that the CDK team may implement something using built-in custom resources magic behind the scenes that abstracts away the complexity of us having to use Custom Resources directly.

This StackOverflow thread explains the problem well and provides a solution in terms of a lambda function backed custom resource for cloudformation. The next part of the puzzle (for me) is how to implement this in CDK!

reidca avatar Oct 03 '19 09:10 reidca

@eladb Is this https://github.com/aws/aws-cdk/blob/master/packages/%40aws-cdk/aws-s3/lib/notifications-resource/notifications-resource.ts intended to solve this problem? Are there any examples of using it?

reidca avatar Oct 07 '19 14:10 reidca

@reidca - No its not, fundamentally CloudFormation only supports two resource types. In order to be able to import a bucket and add event notification targets to it, there would have to be a separate AWS::S3::BucketNotification CloudFormation type.

jd-carroll avatar Nov 02 '19 22:11 jd-carroll

I'll actually take back my previous comment, I think there could be a way to accomplish this using a lambda function.

Here are some high level thoughts:

  • The stack creating the bucket notification should import the bucket so as to create an import / export relationship between the two stacks (this way it is obvious if someone tries to delete the bucket stack)
  • A lambda function would use the SDK to inspect / add the bucket notification to the original bucket. This lambda function would be similar to other singleton functions already created by the CDK and invoked during CloudFormation deployment as a CustomResource.
  • The lambda function would be invoked by the stack requesting the bucket notification (not the stack which creates the bucket)

The caveat would be if the bucket is in a different account. I'm not sure how the permissions would be sorted out for the lambda trying to modify a bucket in a separate account, but it might be possible. (I don't even know if cross account event notification is possible)

jd-carroll avatar Nov 02 '19 23:11 jd-carroll

"A lambda function would use the SDK to inspect / add the bucket notification to the original bucket."

Is there a collection of Custom Resources anywhere in the CDK core where something like this could live? You can do pretty much anything with the SDK even if it's not supported by CloudFormation (after all, that's how tools like Terraform work pretty much). It'd be really helpful if functionality like adding bucket notifications for unowned buckets could be handled "natively" by CDK, sort of like...:


import { S3BucketNotification } from "@aws-cdk/custom-resources";

-- snip --

new S3BucketNotification(this, "<name>", {
    bucket: Bucket.fromBucketArn("...") ,
    events: [...],
    filter_rules: [...],
    target: "..."
});

There's nothing preventing anybody from creating a third-party implementation of this, but having an "official" catalog of solutions for cases where CloudFormation design decisions make other approaches impossible would be quite handy.

michaelmoussa avatar Nov 06 '19 16:11 michaelmoussa

@eladb

I am not sure why addEventNotification function can not be part of IBucket? As it is just using a lambda to setup the bucket notifications, at that would work for existing buckets

Otherwise i did like the "Serverless" implementation of the lambda handler as it makes sure to keep any of the existing bucket notifications. You can see the implementation here: https://github.com/serverless/serverless/tree/master/lib/plugins/aws/customResources/resources/s3

michaelbrewer avatar Jan 23 '20 21:01 michaelbrewer

Also if you destroy the stack it would completely clear out any of the notification configured for that bucket

 if (event.RequestType === 'Delete') {
    props.NotificationConfiguration = { }; // this is how you clean out notifications
  }

michaelbrewer avatar Jan 23 '20 22:01 michaelbrewer

Here's the CustomResource CloudFormation part of the Serverless stack's implementation: https://github.com/serverless/serverless/blob/master/lib/plugins/aws/package/compile/events/s3/index.js#L281

Taken together with the link @michaelbrewer shared: https://github.com/serverless/serverless/tree/master/lib/plugins/aws/customResources/resources/s3

Give a complete picture of how Serverless Framework handles this scenario.

rrrix avatar Apr 28 '20 17:04 rrrix