LocalStack —Test your Lambda on your localhost
As a strong exponent of developer experience ( DX ) I have come to appreciate the use-case where the value of testing lambdas locally is of high value to a developer.
One of the best value that LocalStack provides is allowing developers to test Lambda functions locally before committing it to AWS environment. This provides reasonable confidence of what to expect in actual environment.
The objective of this blog is to provide a basic introduction to usage of lambda on your local machine using LocalStack.
This is going to be short. First make sure your local setup is ready and running localStack.
The steps are described in following introductory blog on LocalStack : https://prabhakar-borah.medium.com/localstack-running-aws-locally-introduction-79923af9d5a8
Create a simple function to test as below,
You can access the file from my repo,
https://github.com/prabhakarit/localstack-test/blob/main/lambda-basic/index.js
Next zip the index.js file and name the compressed file as “api-handler.zip”.
Create a bash script. Add following script to create variables, environment variables and alias for usage with LocalStack.
Than create the lambda function by defining the function name, runtime programming language, handler, memory allocation, zip file for lambda source, and arn of lambda execution role which can be dummy iam role for this example.
Get the lambda arn of the created function for future reference.
Create the api gateway rest-api using following,
Store the API ID and PARENT RESOURCE ID in variables.
Use following commands to define the get method call and create deployment to make lambda accessible.
The url to test will be as follows. Same can be stored to a variable to test the get call.
ENDPOINT=http://localhost:4566/restapis/${API_ID}/${STAGE}/_user_request_/restapis
Now, you can perform curl on the url to confirm working as follows,
curl -i ${ENDPOINT}
The complete bash script can be viewed here,
How to update your lambda ?
Once index.js is updated. Re-create the api-handler.zip file and run the follwing command to update your lambda function. Curl the endpoint once more to confirm the change has reflected.
aws lambda update-function-code — function-name api — zip-file fileb://api-handler.zip
This is a simple yet very useful aspect of LocalStack for running lambda functions locally. The good thing with LocalStack is that lambda serverless related services are under open source or free license. Relevant serverless services such as S3, SQS, SNS, API Gateway, DynamoDB is provided under free license. This provides a good base for developers to test serverless offerings of AWS on localStack without needing to go for a paid one.
LocalStack with Serverless integration provides even better experience with running lambdas. Which however is not in scope of this blog. I will look to cover same in the future.
I hope this quick demo of LocalStack for lambda proves helpful. Have fun !