Getting started with aws lambda
This is brief guide about creating and running very simple function in AWS lambda.
First you need to create a new IAM user for lambda function
aws iam create-role --role-name lambda-ex --assume-role-policy-document '{"Version": "2012-10-17","Statement": [{ "Effect": "Allow", "Principal": {"Service": "lambda.amazonaws.com"}, "Action": "sts:AssumeRole"}]}'
If everything goes well you'll get json output like below, Note the Arn we'll need for next section
{
"Role": {
"Path": "/",
"RoleName": "lambda-ex",
"RoleId": "sldfjaslkdfj",
"Arn": "arn:aws:iam::123:role/lambda-ex",
"CreateDate": "2021-07-14T11:26:11+00:00",
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}
}
}
Create a function which prints Hello World!, Name this file as index.js
exports.handler = async function(event, context) { console.log("Hello World! from AWS lambda"); console.log(`env: ${JSON.stringify(process.env, null, 2)}`); console.log(`event: ${JSON.stringify(event, null, 2)}`); return context.logStreamName }
Compress the file using zip command
zip lambda.zip index.js
Create a function using create-function command (Note: Make sure you are using right arn)
aws lambda create-function --function-name my-function \ --zip-file fileb://lambda.zip --handler index.handler --runtime nodejs12.x \ --role arn:aws:iam::123:role/lambda-ex
If everything goes well we'll get json output like this
{
"FunctionName": "my-function",
"FunctionArn": "arn:aws:lambda:ap-south-1:123:function:my-function",
"Runtime": "nodejs12.x",
"Role": "arn:aws:iam::123:role/lambda-ex",
"Handler": "index.handler",
"CodeSize": 330,
"Description": "",
"Timeout": 3,
"MemorySize": 128,
"LastModified": "2021-07-14T11:36:26.411+0000",
"CodeSha256": "IUUQ31sjIfD48K+jcmmtmnelOHwAhJ3Iaw/y0+hhFWM=",
"Version": "$LATEST",
"TracingConfig": {
"Mode": "PassThrough"
},
"RevisionId": "67b79ab9-507f-4c0d-ae0a-af3e7ae05659",
"State": "Active",
"LastUpdateStatus": "Successful",
"PackageType": "Zip"
}
Invoke function using invoke command
aws lambda invoke --function-name my-function out --log-type Tail
You'll get json output something like this
{
"StatusCode": 200,
"LogResult": "abc",
"ExecutedVersion": "$LATEST"
}
Note that LogResult is base64 encoded data, Since I am using Emacs I just use base64-decode-region from my Eshell