In this step we create a new Lambda function that resizes the image after the user uploads it.
ImageResizer:
Type: AWS::Serverless::Function
Properties:
CodeUri: fcj-book-shop/resize_image/function.zip
PackageType: Zip
Handler: index.handler
Runtime: nodejs16.x
FunctionName: resize_image
Architectures:
- x86_64
Policies:
- Statement:
- Sid: ResizeUploadImage
Effect: Allow
Action:
- s3:GetObject
- s3:PutObject
- s3:DeleteObject
Resource:
- arn:aws:s3:::book-image-shop/*
- arn:aws:s3:::book-image-resize-shop/*
Events:
ResizeImage:
Type: S3
Properties:
Bucket: !Ref BookImageShop
Events: s3:ObjectCreated:*
Environment:
Variables:
WIDTH: 200
HEIGHT: 280
DES_BUCKET: book-image-resize-shop
If you create S3 bucket names that are different from the ones in the lab, please check Policies | Resources or Environment of resources and update.
Add the following script at the end of the file to grant permission to the books-image-shop bucket to use this function
LambdaInvokePermission:
Type: "AWS::Lambda::Permission"
Properties:
FunctionName: !GetAtt ImageResizer.Arn
Action: "lambda:InvokeFunction"
Principal: "s3.amazonaws.com"
SourceAccount: !Sub ${AWS::AccountId}
SourceArn: !GetAtt BookImageShop.Arn
The directory structure is as follows:
fcj-book-shop
├── fcj-book-shop
│ ├── books_list
│ │ └── books_list.py
│ ├── book_create
│ │ └── book_create.py
│ ├── book_delete
│ │ └── book_delete.py
│ ├── resize_image
│ └── function.zip
└── template.yaml