Create a Lambda function With AWS Command Line Interface

Souvik Paul
Oct 27 · 6 min read
Image for post
Image for post

AWS Lambda is a serverless computing service that lets the user to run code without provisioning or managing servers and the user needs to pay for how much they use. The user can also scale it up and down according to their needs.

There are many methods to create a Lambda function like using Lambda console in the browser, using AWS CLI, using Terraform etc.

In this blog, we are going to learn the process of creating a Lambda function using AWS Command Line Interface.

Prerequisites

  1. You should have an AWS account.
  2. You should have a basic knowledge of Node.js, as our lambda function will be based on that.
  3. AWS CLI should be installed in your system. Check out the installation procedure here.

Procedure

Step 1: First of all we’ll create a directory in our local machine with any name that we like. Here we will name it as Project. Inside this directory, we’ll create a file named trust-policy.json and open it in a text editor.Then, we’ll copy the following JSON into it.

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
}

Step 2: Now, we’ll create the execution role. It is an AWS Identity and Access Management (IAM) role that gives our function permission to access AWS resources. To create this role, we’ll use the following command —

$ aws iam create-role --role-name lambda_role --assume-role-policy-document file://trust-policy.json

Here, trust-policy.json allows Lambda to use the role’s permissions by giving the service principal lambda.amazonaws.com permission to call the AWS Security Token Service AssumeRole action.

The output of the above command will be like this —

{
"Role": {
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
}
}
]
},
"RoleId": "TYRUWEHGDHCBNUHFGB3YTT",
"CreateDate": "2020-10-27T04:35:35Z",
"RoleName": "lambda_role",
"Path": "/",
"Arn": "arn:aws:iam::678492537495:role/lambda_role"
}
}

Step 3: Now that we have created the role, we’ll attach permission to this role using the following command.

$ aws iam attach-role-policy --role-name lambda_role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole

AWSLambdaBasicExecutionRole policy gives permission to the Lambda function to write logs to CloudWatch.

Step 4: In the Project directory, we’ll create a file named index.js with the following code —

exports.handler = async(event) => {
console.log(event);
console.log("Hello world, This is Lambda");
}

Now, in the same directory, we’ll zip this file into a package using any zipping software or using the following command —

$ zip lambdaFunc.zip index.js

Now, we’ll deploy this zip file and create a lambda function using the following command —

$ aws lambda create-function --function-name funcZero \ 
--zip-file fileb://lambdaFunc.zip --handler index.handler \
--runtime nodejs12.x \
--role arn:aws:iam::678492537495:role/lambda_role \
--region=ap-south-1

The highlighted text in the role ARN should be replaced by your account ID.

The above command will create a lambda function with the name of funcZero and it will include the code from the zip file named lambdaFunc.zip. In the handler, index is the name of the code file (index.js) and handler is the method name.

The above command will create the lambda function with the following output in the CLI —

{
"LastUpdateStatus": "Successful",
"FunctionName": "funcZero",
"LastModified": "2020-10-27T06:16:39.720+0000",
"RevisionId": "2d76f76f-5a3c-3125-785b-e41bab784695",
"MemorySize": 128,
"State": "Active",
"Version": "$LATEST",
"Role": "arn:aws:iam::678492537495:role/lambda_role",
"Timeout": 3,
"Runtime": "nodejs12.x",
"TracingConfig": {
"Mode": "PassThrough"
},
"CodeSha256": "YPkPou/xMr8aoY+qpas/XbMhM40Rguy5JopGFY6zN6y=",
"Description": "",
"CodeSize": 306,
"FunctionArn": "arn:aws:lambda:ap-south-1:678492537495:function:funcZero",
"Handler": "index.handler"
}

Step 5: Now, we will list all the lambda functions that are present in our account using the following command —

$ aws lambda list-functions --region=ap-south-1

Since, till now we have created only one function, so above command will also display only one function in the output, which is given below.

{
"Functions": [
{
"TracingConfig": {
"Mode": "PassThrough"
},
"Version": "$LATEST",
"CodeSha256": "YPkPou/xMr8aoY+qpas/XbMhM40Rguy5JopGFY6zN6y=",
"FunctionName": "funcZero",
"MemorySize": 128,
"RevisionId": "2d76f76f-5a3c-3125-785b-e41bab784695",
"CodeSize": 306,
"FunctionArn": "arn:aws:lambda:ap-south-1:678492537495:function:funcZero",
"Handler": "index.handler",
"Role": "arn:aws:iam::678492537495:role/lambda_role",
"Timeout": 3,
"LastModified": "2020-10-27T06:16:39.720+0000",
"Runtime": "nodejs12.x",
"Description": ""
}
]
}

Step 6: We can also log in to the lambda console to confirm whether the function has been created or not.

If we want to download the deployment package into our system, i.e. the lambdaFunc.zip file that we have uploaded earlier in step 4, we’ll use the following command —

$ aws lambda get-function --function-name funcZero --region=ap-south-1

This will give a text in json format as the output, which will have a link in it. This link can be copied and pasted in the address bar of the browser to download the zip file.

Step 7: Now we’ll invoke our lambda function synchronously, which is also called as synchronous invocation.

When a lambda function is invoked synchronously, lambda runs the function and waits for a response. When the function completes, Lambda returns the response from the function’s code with additional data, such as the version of the function that was invoked. To invoke a function synchronously with the AWS CLI, we’ll use the invoke command.

$ aws lambda invoke --function-name funcZero \ 
--payload '{ "key": "value" }' response.json --region=ap-south-1

The payload is a string that contains an event in JSON format. The name of the file where the AWS CLI writes the response from the function is response.json.

The above command will give the following output in the terminal —

{
"ExecutedVersion": "$LATEST",
"StatusCode": 200
}

This output includes the version that processed the event, and the status code returned by Lambda. If Lambda is able to run the function, the status code will be 200, even if the function returned an error.

If Lambda isn’t able to run the function, the error is displayed in the output.

Now, we’ll print the logs for an invocation in the terminal. For that we’ll use the following command —

$ aws lambda invoke --function-name funcZero out --log-type Tail \ 
--region=ap-south-1

The above command will return a response which includes a LogResult field that contains up to 4 KB of base64-encoded logs from the invocation, which is displayed below —

{
"LogResult": "U1RBUlQgUmVxdWVzdElkOiA2Yjc0MjdiYy03MWMzLTQxNTMtOTcyYi03MDUwMjk1YzY4NzggVhfhfjhjfhkfhnvmnx,mvniKHGFKJHSNCSNKLK;LSDSKSKQT1JUIFJlcXVlc3RJZDogNmI3NDI3YmMtNzFjMy00MTUzLTk3MmItNzA1MDI5NWM2ODc4CUR1cmF0aW9uOiAzOS4wMiBtcwlCaWxsZWQgRkJKSDFHSKJDFHKFHFYYFGRGSJHGJHGHsjgFSHGF=",
"ExecutedVersion": "$LATEST","StatusCode": 200}

To decode the above logs, we’ll use base64 utility in the following command-

$ aws lambda invoke --function-name funcZero out --log-type Tail --region=ap-south-1 --query 'LogResult' --output text |  base64 -d

The above command will give an output as displayed below-

Image for post
Image for post

Step 8: Now we’ll invoke our lambda function asynchronously, which is also called as asynchronous invocation.

When we invoke a function asynchronously, we don’t wait for a response from the function code. We hand off the event to Lambda and Lambda handles the rest. For asynchronous invocation, Lambda places the event in a queue and returns a success response without additional information. A separate process reads events from the queue and sends them to the function. To invoke a function asynchronously, we’ll set the invocation type parameter to Event.

We’ll use the following command to invoke the function asynchronously-

$ aws lambda invoke --function-name funcZero  --invocation-type Event --payload '{ "key": "value" }' response.json --region=ap-south-1 

The output file (response.json) doesn't contain any information, but is still created when we run this command. If Lambda isn't able to add the event to the queue, the error message appears in the command output.

So, in our case, the above command will give the following output in the terminal -

{     
"StatusCode": 202
}

Lambda manages the function’s asynchronous event queue and attempts to retry on errors. If the function returns an error, Lambda attempts to run it two more times, with a one-minute wait between the first two attempts, and two minutes between the second and third attempts. Function errors include errors returned by the function’s code and errors returned by the function’s runtime, such as timeouts.

Step 7: So, everything is done, now we can delete this function using the following command —

$ aws lambda delete-function --function-name funcZero --region=ap-south-1

Summary

In this article, we have understood the concept of AWS Lambda, created a role and attached a policy to it for the lambda function. then we’ve created a file which contains the code and the same has been deployed in a zip file using the CLI. We’ve also understood how to list all the lambda functions present in our account and how to download the deployment package. then we’ve learnt to invoke the function synchronously and asynchronously. Finally, we have learnt how to delete the lambda function.

For this project, I took help from the AWS Lambda documentation. Particularly, Using AWS Lambda with the AWS Command Line Interface.

References:

The Startup

Medium's largest active publication, followed by +730K people. Follow to join our community.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store