Run Server-less code via AWS Lambda

Mohit Sharma
Sharmio
Published in
11 min readJan 29, 2021

--

After a long delay, I come back again with another article called “Run a serverless code using AWS lambda.”

In this article, you will learn the basics of running code on AWS Lambda without provisioning or managing servers. Let’s start with an intro.

AWS Lambda is an event-driven, serverless computing platform provided by Amazon as a part of Amazon Web Services. It is a computing service that runs code in response to events and automatically manages the computing resources required by that code. It was introduced in November 2014 While writing a blog, I assume you’ve little knowledge or no knowledge about AWS Lambda.

Step 1:

All you need is the AWS Account.

Now, I will walk through how to create a Lambda function using the AWS Lambda console. I will then show you how to manually invoke the Lambda function using sample event data and review your output metrics. Everything done in this tutorial is free tier eligible. So, don’t worry about any cost.

Step2:

Once your account has been created and after login, you’ll see this screen.

Go to the above services drag button. And type “lambda” then press enter.

Now, hopefully, we are on the same page.

Step3:

Creating a lambda function from the console.

Now, AWS lambda provides you with three different function option

  • Author from scratch: Hello World examples include just enough code for your chosen language to get you started. You can add triggers and configure additional settings later.
  • Use a blueprint: Blueprints are language-specific samples that include function code and settings for a runtime and trigger combination. Blueprints are available for Node.js and Python runtimes.
  • Browse serverless app repository: Sample applications from the AWS Serverless Application Repository are fully functional Lambda applications. They use the AWS Serverless Application Model (AWS SAM) with AWS CloudFormation and include an execution role, function trigger, and other resources.

For the explanation purpose, I’ll use the second option that is “Use a Blueprint”. After selecting the blueprint option I’ve added the filter “hello-world” see the image below.

Now, based on your knowledge and skill-set, choose the function and click the button “configure” right side at the bottom. Below, I am showing you both

  1. hello-world — A starter AWS Lambda function using node.js

2. hello-world-python — A starter AWS Lambda function

Based on your knowledge and skill-set, choose the function and click the button “configure” right side at the bottom. Now, just type your function name. And, choose Execution role with basic lambda permissions. (For developers if you’ve existing role that you’ve created to be used with this Lambda function. The role must have permission to upload logs to Amazon CloudWatch Logs. “Use an existing role”)

Note: there are some criteria while writing the name. Name can contain only letters, numbers, hyphens, and underscores. Maximum length is 64 character and so on.

Now, let’s explore the last execution role “Create a new role from AWS policy templates”

A Lambda function consists of code you provide, associated dependencies, and configuration. The configuration information you provide includes the compute resources you want to allocate (for example, memory), execution timeout, and an IAM role that AWS Lambda can assume to execute your Lambda function on your behalf.

In option three You will need to enter Basic Information about your Lambda function.

Basic Information:

  • Name: You can name your Lambda function here. For this blog, we are creating myfirstlambda_function.
  • Role name: type any name of your own choice for example lambda_basic_execution. Note: Use only letters, numbers, hyphens, or underscores with no spaces.
  • Policy template: AWS offers managed permissions policies that you can add to your IAM role. Choose all the policies that apply to your function.

see the image above I choose three policy template at the moment. (Don’t worry if you are not able to understand everything at the moment because we are not going to use this option “later blogs we will going to see this option”)

Before, you click the create function button at the bottom. I would like to tell you again that we are going with the first option.

Lambda Function Code:

  • In this above image, I am showing you the section, which you can review the example code authored in Python.

Now, go to the bottom of the page and select Create Function.

Hurray!!!! You have created your first lambda function #Excited

Step4:

Now, you see the Designer at the top. The designer shows an overview of your function and its upstream and downstream resources. You can use it to configure triggers, layers, and destinations. (Note:- Configuring triggers, layers etc. is beyond the scope of this blog because I am assuming you are very naive at the moment. Soon, in coming few weeks we are going to do our hands dirty while using AWS lambda)

Function code is used to edit code, click on the function in the visual config view, and scroll down to see the editor or use the Ctrl/Cmd-Shift-F keyboard shortcut to switch to a full-screen code editor.

Full-screen mode using Ctrl/Cmd-Shift-F keyboard shortcut

Tip: Try to make your hands dirty with this function code before moving forward!

Runtime: Currently, you can author your Lambda function code in Java, Node.js, C#, Go, Python or Ruby. For this tutorial, leave this on Python 3.7 as the runtime.

Handler: You can specify a handler (a method/function in your code) where AWS Lambda can begin executing your code. AWS Lambda provides event data as input to this handler, which processes the event.

The filename.handler-method value in your function. For example, “main.handler” calls the handler method defined in main.py.

In this example, Lambda identifies this from the code sample and this should be pre-populated with lambda_function.lambda_handler.

Environment Variable (optional)

Note — As a beginner with AWS lambda you don’t need to worry about this at the moment. In later blogs, we will be going to create this as well.)

You can use environment variables to store secrets securely and adjust your function’s behaviour without updating code. An environment variable is a pair of strings that are stored in a function’s version-specific configuration. The Lambda runtime makes environment variables available to your code and sets additional environment variables that contain information about the function and invocation request.

In order to call the environment variables in your function code, use the standard method for your programming language (Python, Go, Ruby etc.)

Retrieve environment in function code using Python

Scroll down to configure your memory, timeout, and VPC settings. For this blog, leave the default Lambda function configuration values

Step5:

Invoking the lambda function and validating our results

Now, you can test the function, verify results, and review the logs. Select Configure Test Event from the drop-down menu called “Select a test event”

The editor pops up to enter an event to test your function.

  • Choose Hello World from the Sample event template list from the Input test event page.
  • Type in an event name like myfirstlambdaevent.
  • You can change the values in the sample JSON, but don’t change the event structure. For this blog, replace value1 with hello, value 2 with the world! and value 3 with “AWS Lambda is an event-driven, serverless computing platform provided by Amazon as a part of Amazon Web Services.”.

Select Create, then select Test

Hurray!!! Successfully run !!!

Note in the result you may be getting hello only not the whole sentence because in the default python template in function code we are returning key1, not key2 and key3.

In order to retrieve all the sentences pass all the key values.

see the return statement now

Note: Before clicking the test button every time you have to click the save button at the top. If you don’t do that, changes are not reflecting back to your output.

Hurray!!! Now, we received all three values

  • The Execution results section verifies that the execution succeeded.
  • The Summary section shows the key information reported in the Log output.
  • The Log output section will show the logs generated by the Lambda function execution

Step6:

Select Monitoring to view the results. AWS Lambda automatically monitors Lambda functions and reports metrics through Amazon CloudWatch.

What is Cloud Watch?

CloudWatch collects monitoring and operational data in the form of logs, metrics, and events, providing you with a unified view of AWS resources, applications, and services that run on AWS and on-premises servers. More Details.

Cloud Watch helps us to monitor our code as it executes, Lambda automatically tracks the number of requests, the latency per request, and the number of requests resulting in an error and publishes the associated metrics. When you invoked the Lambda function a few more times by repeatedly clicking the Test button. This will generate the metrics that can be viewed in the below image.

Note: Lambda metrics are reported through Amazon CloudWatch. You can leverage these metrics to set custom alarms (soon creating a video on how to create billing alarm on my youtube channel). The Monitoring tab will show you six CloudWatch metrics: Invocation count, duration, errors, invocations, Asynchronous delivery failure, and Iterator errors. With AWS Lambda, you pay for what you use. After you hit your AWS Lambda free tier limit, you are charged based on the number of requests for your functions (invocation count) and the time your code executes (invocation duration).

Step 7:

While you will not get charged for keeping your Lambda function, you can easily delete it from the AWS Lambda console. Go to the action button and click on “Delete function”

AWS ask you for confirmation before deleting. Just go ahead and click delete.

Congratulations!! For reaching this far with me. Now, you have created your first AWS Lambda function. This is your first step in learning how to run applications without needing to provision or manage servers (like EC2). Lambda automatically scales your applications by running your code in response to each trigger, scaling precisely with the size of your workloads.

Now, in the next coming weeks, we will be going to do some intermediate level of work using AWS lambda. Till then, try to understand each concept. Let me know if you have any more questions.

For latest updates connect with me on -

LinkedIn | Twitter | GitHub |Facebook | Instagram | YouTube

👋 Join FAUN today and receive similar stories each week in your inbox! Get your weekly dose of the must-read tech stories, news, and tutorials.

Follow us on Twitter 🐦 and Facebook 👥 and Instagram 📷 and join our Facebook and Linkedin Groups 💬

If this post was helpful, please click the clap 👏 button below a few times to show your support for the author! ⬇

--

--

Mohit Sharma
Sharmio

Entrepreneur, Innovator & Engineer @Sharmio