Add additional configuration to an s3 bucket with a dynamic name

I had the same issue and ended up following the guidance from @eahefnawy in issue #2967.

The answer is not to define an S3 event with the function…since serverless attempts to create a new S3 bucket…but to manually define the NotificationConfiguration in the S3 bucket resource, as well as a corresponding Lambda permission resource. (This solution relies on the CloudFormation naming convention used by serverless for Lambda functions.) In your case, it would look something like:

functions:
  foo:
    handler: handler.foo

resources:
  Resources:
    S3BucketMyBucketDev:
      DependsOn:
        - FooLambdaPermissionS3BucketMyBucketDevS3
      Type: AWS::S3::Bucket
      Properties:
        BucketName: my-bucket-${self:provider.stage}
        CorsConfiguration:
          CorsRules:
            - AllowedHeaders:
                - "*"
              AllowedMethods:
                - GET
              AllowedOrigins:
                - "*"
        NotificationConfiguration:
          LambdaConfigurations:
            - Event: "s3:ObjectCreated:*"
              Function:
                "Fn::GetAtt": [ FooLambdaFunction, Arn ]
    FooLambdaPermissionS3BucketMyBucketDevS3:
      DependsOn:
        - FooLambdaFunction
      Type: AWS::Lambda::Permission
      Properties:
        FunctionName:
          "Fn::GetAtt": [ FooLambdaFunction, Arn ]
        Action: "lambda:InvokeFunction"
        Principal: "s3.amazonaws.com"
        SourceArn: "arn:aws:s3:::my-bucket-${self:provider.stage}"
3 Likes