In this step we create a new Lambda function that resizes the image after the user uploads it.
Open template.yaml file in fcj-book-shop folder.
Add the following script at the end of the file to create resizing image function.
Firstly, we will create width and height parameters.
width:
Type: String
Default: 200px
height:
Type: String
Default: 280px
Then, we add the following scripts to create ImageResize function.
ImageResize:
Type: AWS::Serverless::Function
Properties:
CodeUri: fcj-book-shop/resize_image/function.zip
PackageType: Zip
Handler: index.handler
Runtime: nodejs20.x
FunctionName: resize_image
Architectures:
- x86_64
Policies:
- Statement:
- Sid: ResizeUploadImage
Effect: Allow
Action:
- s3:GetObject
- s3:PutObject
- s3:DeleteObject
Resource:
- !Sub "arn:aws:s3:::${bookImageShopBucketName}/*"
- !Sub "arn:aws:s3:::${bookImageResizeShopBucketName}/*"
Events:
ResizeImage:
Type: S3
Properties:
Bucket: !Ref BookImageShop
Events: s3:ObjectCreated:*
Environment:
Variables:
WIDTH: !Ref width
HEIGHT: !Ref height
DES_BUCKET: !Ref BookImageResizeShop
Next, add the following script at the end of the file to grant permission to the book-image-shop-by-myself bucket to use this function.
ImageResizeInvokePermission:
Type: "AWS::Lambda::Permission"
Properties:
FunctionName: !Ref ImageResize
Action: "lambda:InvokeFunction"
Principal: "s3.amazonaws.com"
SourceAccount: !Sub ${AWS::AccountId}
SourceArn: !GetAtt BookImageShop.Arn
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.
The directory structure is as follows.
fcj-book-shop
├── fcj-book-shop
│ ├── books_list
│ │ └── books_list.py
│ ├── book_create
│ └── requirements.txt
│ │ └── book_create.py
│ ├── book_delete
│ │ └── book_delete.py
│ ├── resize_image
│ └── function.zip
└── template.yaml