generic approach to package dependencies for Lambda
steps involved
- create funtion
- create terraform - to create s3 bucket, create lambda role, zip the source code and upload the function
- test terraform
- create api gateway
- integrate the api gateway with lambda funtion
- terraform init
- terraform appy
- terraform destroy (run destroy when you are ready to clean up resources)
- aws lambda invoke --region=us-west-1 --function-name=hello response.json
- cat response.json
now modify the function.js and run terraform apply to retrigger the deployment . sequence of commands
- terraform apply
- aws lambda invoke --region=us-west-1 --function-name=hello response.json
- cat response.json
now create api gateway version 2. using terraform. AWS API Gateway is a fully managed service that makes it easy for developers to create, publish, maintain, monitor, and secure APIs at any scale.
- create api gateway - api-gateway.tf
- integrate the api gateway with lambda funtion - hello-api-gateway.tf
- curl "https://<id>.execute-api.us-west-1.amazonaws.com/dev/hello?Name=Vito%20Croleone"
note: %20 represents a space in URL - as space is assigned number 32 which is 20 in hexadecimal
-curl -X POST \
-H "Content-Type: application/json" \
-d '{"name":"Vito Corleone"}' \
"https://<id>.execute-api.us-west-1.amazonaws.com/dev/hello"
-
- s3 bucket
-
- api gateway and routes GET and POST
-
- cloudwatch logs
How to move dependencies into AWS lambda environment? Lets consider an eg: Reading a new file in an S3 bucket using aws sdk libs steps involved:
- 1.create a node project and add external dependencies (npm init)
-
- grant access to this function to read a file in a new S3 bucket
-
- create lambda funtion using terraform - s3-lambda.tf
-
- simple wrapper around terraform to deploy from local
-
- make the script executable - chmod +x terraform.sh
-
- finally run the script - ./terraform.sh to test from local
-
- invoke this new s3 function and provide a json payload with the bucket name and the object
Test running terraform apply and check the outputs.
hello_base_url = "https://<id>.execute-api.us-west-1.amazonaws.com/dev"
test_s3_bucket = "<bucket-name>"
TEST invoking lambda using AWS CLI
aws lambda invoke --region=us-west-1 --function-name=s3 \
--cli-binary-format raw-in-base64-out \
--payload '{"bucket":"test-<your>-<name>","object":"hello.json"}' \
response.json
'{"bucket":"test-literate-silkworm","object":"hello.json"}'