Run Serverless code via AWS Lambda

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

In this blog, you will learn the basics of running code on AWS Lambda without provisioning or managing servers. Those of you don’t know what is AWS Lambda? Let me tell you in short.

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.Create and Activate an AWS AccountI’m getting started with Amazon Web Services. How do I create and activate a new AWS account? Create your account Go to…aws.amazon.com

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.

Image for post

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

Image for post

Now, hopefully, we are on the same page.

Image for post

Step3:

Creating a lambda function from the console.

Image for post

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.
Image for post

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.

Image for post

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
Image for post

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

Image for post

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.

Image for post

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.
Image for post

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”)

Image for post

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.

Image for post

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

Image for post

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)

Image for post

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.

Image for post

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

Image for post

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

Image for post

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.

Image for post

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.

Image for post

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

Image for post
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

Image for post

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”

Image for post

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

Image for post
  • 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

Image for post

Hurray!!! Successfully run !!!

Image for post

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.

Image for post

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

Image for post

see the return statement now

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

Hurray!!! Now, we received all three values

Image for post
  • 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.

Image for post

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.

Image for post
Image for post

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, errorsinvocations, Asynchronous delivery failure, and Iterator errorsWith 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”

Image for post

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

Image for post
Image for post

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.

Leave a Comment

Your email address will not be published. Required fields are marked *

Close Bitnami banner
Bitnami