I want to create a Lambda function that is triggered from a S3 bucket created within the same CloudFormation stack but cannot get the syntax quite right.
The event should only be fired when an object is uploaded to /uploads
. I also need to specify some bucket properties (CORS).
S3 bucket definition in resources
resources:
Resources:
myBucket:
Type: AWS::S3::Bucket
Properties:
BucketName: my-bucket
# CORS properties...
Event in function definition:
events:
- s3:
bucket: myBucket
event: s3:ObjectCreated:Put
rules:
- prefix: uploads/
I do not want to use existing: true
because it creates some helper objects for this simple task. I cannot find any documentation or examples that fit my case.
CodePudding user response:
The existing:true
flag only relates to S3 buckets created outside of your serverless project, for buckets that already exist, which is not the case here.
The situation you face is that you can't use the typical serverless framework convenience of defining the bucket in the Lambda event trigger, like this:
functions:
users:
handler: users.handler
events:
- s3:
bucket: photos
event: s3:ObjectRemoved:*
The reason that you can't use that method is that it creates the photos
bucket and does not allow you to supply additional bucket configuration, e.g. CORS or bucket policy.
The solution to this is to create the S3 bucket in the S3 provider configuration, with CORS policy, and then refer to the bucket from your Lambda function event configuration. For example:
provider:
s3:
photosBucket:
name: photos
versioningConfiguration:
Status: Enabled
corsConfiguration:
CorsRules
- rule1 here