AWS Lambda (Python) Packaging Methods
1. Package Creation
First, let's create deployment packages for deploying to Lambda.
Use poetry
, a Python package management tool, to install the libraries already registered in serverless-backend-application-stack-python
[ec2-user ~]cd serverless-backend-application-stack-python/
[ec2-user ~]poetry install
The catalog AMI includes Shell Scripts (build-app.sh
and build-layer.sh
) that automatically create packages for you. When executed, deployment zip files are generated as follows.
# Execute Shell Script
./build-app.sh
.dist/app/sample-api/app.zip
.dist/app/sample-event/event.zip
2. Create Deployment Bucket
Create a dedicated bucket so that Lambda source code packages can be uploaded to S3 bucket and referenced from CloudFormation.
[ec2-user ~]ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)
[ec2-user ~]BUCKET_NAME="code-bucket-${ACCOUNT_ID}"
[ec2-user ~]aws s3api create-bucket \
--bucket $BUCKET_NAME \
--region us-east-1 \
--create-bucket-configuration LocationConstraint=<your region> #Add this option when creating outside us-east-1
3. Deploy Package and Upload to S3
Upload source code packages to the created bucket
[ec2-user ~]aws s3 cp .dist/app/sample_api/api.zip s3://$BUCKET_NAME
[ec2-user ~]aws s3 cp .dist/app/sample_event/event.zip s3://$BUCKET_NAME
4. Creating Lambda Layer
Since the libraries used will be deployed to Lambda Layer, please execute the following script. Lambda Layer will be created automatically. Please provide the deployment region as an argument. It is required that the application deployment region and the Lambda Layer region be aligned.
# Execute Shell Script
./build-layer.sh us-east-1
When you execute the shell script, two ARN responses are returned. When you try AWS CloudFormation deployment, you need to specify LayerVersionArn values like the following, so please make a note of them.
"LayerVersionArn": "arn:aws:lambda:us-east-1:<Account ID>:layer:psycopg3-layer:1"
"LayerVersionArn": "aws:lambda:us-east-1:<Account ID>:layer:python-lambda-application-template-lib-layer:1 "