How to add S3 trigger event on AWS Lambda function using Serverless framework?

Ronit kadwane picture Ronit kadwane · Jun 29, 2017 · Viewed 9k times · Source

I want to add trigger event on a Lambda function on an already existing bucket and for that I am using below configuration:

 events:
      - s3:
          bucket: serverlesstest
          event: s3:ObjectCreated:*
          rules:
            - prefix: uploads/
            - suffix: .pdf

where bucket serverlesstest is already existing on S3.

This configurations is throwing the error:

An error occurred while provisioning your stack: S3BucketServerlesstest - serverlesstest already exists.

How can I resolve this error using Serverless Framework?

Answer

yabaiwebyasan picture yabaiwebyasan · Feb 27, 2018

It’s not currently possible in the core framework because of CloudFormation behavior. maybe.

But you can use this plugin.

https://github.com/matt-filion/serverless-external-s3-event

After installing serverless-plugin-existing-s3 by npm install serverless-plugin-existing-s3.

And add plugins to serverless.yml

plugins:
  serverless-plugin-existing-s3

Give your deploy permission to access the bucket.

provider:
  name: aws
  runtime: nodejs4.3
  iamRoleStatements:
    ...
    -  Effect: "Allow"
       Action:
         - "s3:PutBucketNotification"
       Resource:
         Fn::Join:
           - ""
       - - "arn:aws:s3:::BUCKET_NAME or *"

And use existingS3 event, it is not just s3.

functions:
  someFunction:
    handler: index.handler
    events:
      - existingS3:
          bucket: BUCKET_NAME
          events:
            - s3:ObjectCreated:*
          rules:
            - prefix: images/
            - suffix: .jpg

After sls deploy command, You can attach event by using sls s3deploy command.

Feature Proposal

it will be added someday in the future.

https://github.com/serverless/serverless/issues/4241