The steps below show how to setup an AWS Lambda function using AWS SAM CLI for Python. The setup takes one through the process of initialization, building, deploying and debugging a AWS Lambda function. The default SAM template also creates an API endpoint for testing the Lambda function. This testing can be done locally, and after deploying the function to AWS. While most of the instructions are easily found on the AWS docs, the instructions for debugging through VS Code and testing using Postman are not well-documented. Please install SAM CLI and read the AWS SAM python deployment guide.
sam init
This initializes the AWS SAM CLI using the configuration wizard that asks questions related to the runtime, name, deployment region etc. The file template.yaml
in the directory created can be edited reflect your requirements, like changing GET to POST, change the function name, API endpoint path etc.
sam build
This create a deployment package ready for deployment. You will need to build everytime you make change to the app.py
file in the function directory. This creates a directory .aws-sam/build
with the required python packages, and deploy copy of app.py
. This file is ephemeral and make changes to file only for debugging. Any changes will be lost of running sam build
again. If you plan to debug your function, then add the python package ptvsd
on a new line in the requirements.txt
in the function directory.
sam deploy --guided
This will deploy the AWS Lambda function to AWS and create an endpoint.
Debugging in VS Code
- Use the following as the
launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "SAM CLI Python Hello World",
"type": "python",
"request": "attach",
"port": 5890,
"host": "localhost",
"pathMappings": [
{
"localRoot": "${workspaceFolder}/your_function_name/.aws-sam/build/HelloWorldFunction",
"remoteRoot": "/var/task"
}
]
}
]
}
Replace your_function_name
above with the name of the function.
- Now add the following code in the
app.py
in the.aws-sam/build/HelloWorldFunction
directory.
import ptvsd
# Enable ptvsd on 0.0.0.0 address and on port 5890 that we'll connect later with our IDE
ptvsd.enable_attach(address=('0.0.0.0', 5890), redirect_output=True)
ptvsd.wait_for_attach()
- Then start the API locally in debug mode using:
sam local start-api -d 5890 --debug
This will need docker desktop to be working locally.
- Now visit the API endpoint using the browser or Postman.
localhost:3000/your_function_name
- Now press the "Run" button from the Run tab in VS code. This will pause the code at the breakpoint in your
app.py
and you can proceed by stepping through the code.