AWS Lambda is one of the leading serverless architectures in the cloud today. It was first-to-market among the major cloud vendors, offers the most competitive pricing, and is employed by Netflix, one of the largest cloud service providers in existence.

In this tutorial, you’ll set up your first AWS Lambda function. You’ll create a service, add a few lines of code, and test it from inside the AWS console. As you progress throughout the tutorial, you’ll also learn why Lambda and Function-as-a-Service have enjoyed widespread adoption over the past few years.

A lambda sign in the aws boxes signifying aws lambda tutorial

What Is AWS Lambda?

AWS Lambda is a way to run code without creating, managing, or paying for servers. You supply AWS with the code required to run your function, and you pay for the time AWS runs it, and nothing more.

Your code can access any other AWS service or it can run on its own. While there are some rules about how long a function has to respond to a request, there’s almost no limit to what your Lambda can do.

The real power, though, comes from the scalability that Lambda offers you. AWS will scale your code for you, depending on the number of requests it receives. Not having to build and pay for servers is nice. Not having to build and pay for them when your application suddenly goes viral can mean the difference between survival and virtual death.

Let’s get started with creating your first function.

AWS Lambda Tutorial

AWS Account

The first thing you’ll need to create a Lambda function is an AWS account if you don’t already have one. The good news is that Amazon makes it very easy to create a login, and you can complete this tutorial using AWS’ free tier. Your Lambda function’s first million requests are free!

Go to the AWS Management Console and create an account.

Once you have an account, log in to AWS.

Create a Lambda

Once you’re at the console, you can start setting up your function. Click on the services menu near the upper right-hand side of the page. Then, you’ll see an entry for Lambda under the Compute menu.

Click the Lambda entry, and AWS will take you to your Lambda console. Here’s mine.

If you have a new account, your console will be empty. Either way, click the Create Function button.

Before you proceed, let’s cover some more basics.

Lambda Functions

Before you create a Lambda function, you need to identify its inputs and triggers, choose a runtime environment, and decide what permissions and role the service will use.

Lambda functions accept JSON-formatted input and usually respond using the same format. The contents of your function’s input and output are closely tied to the event source that will trigger your function.

An obvious event source is a web request. Lambdas can be set up as an HTTP service. But they are capable of a responding to events from within AWS infrastructure, including Alexa, Cloudfront, Simple Storage Service, and the Simple Email Service.

You also need to select a runtime for your function. AWS Lambda supports Java, Go, PowerShell, Node.js, C#, Python, and Ruby. There’s also a Runtime API you can use for other programming languages.

Finally, your function will need an AWS role. This role defines the entitlements the function has within the AWS platform. AWS security is a deep enough topic that it deserves a series of articles of its own. We’ll use one of the predefined roles AWS offers for new functions.

Pick a Blueprint

Now it’s time to finishing creating your function. You’ll use Python for this function because you can enter the code right into the console.

First, select the Use a Blueprint box in the center of the Create Function page.

Then, type Hello in the search box.

Press enter and AWS will search for blueprints with Hello in the name. One of them will be hello-world-python. Select this and click Configure.

Configure and Create Your Function

This will take you to a form where you will name your function, select a role, and edit the Python code.

Enter a name and select the role indicated in the screenshot above.

Let’s take a quick look at the Python code included in the blueprint.

import json

print('Loading function')

def lambda_handler(event, context):
    print("Received event: " + json.dumps(event, indent=2))
    print("value1 = " + event['key1'])
    print("value2 = " + event['key2'])
    print("value3 = " + event['key3'])
    return event['key1']  # Echo back the first key value
    #raise Exception('Something went wrong')

AWS will call the lambda_handler function each time an event is triggered. This function prints the values associated with three JSON fields: “key1,” “key2,” and “key3.” Before creating the function, remove the # from line seven, so the code looks like it does above.

Click the Create Function button at the bottom of the form.

You’ve created a Lambda function! Now it’s time to test it. Fortunately, AWS makes this very easy.

Test Your Lambda Function

Now, let’s follow the instructions at the top of the page. Click the Test button. AWS will display a form that looks similar to this:

This test will pass a simple JSON document to your function with the three keys it expects set to “value1,” “value2,” and “value3.” That’s good enough for a start. Click the Create button at the bottom.

AWS saves your test, and you can run it from the function page with the Test button. This makes it easy to set up different test cases and run them by name.

Click the test button. AWS will run your test and display a result box.

The test succeeded, and you can see your log result if you click the details disclosure icon.

Here they are:

START RequestId: a334e3ba-27ec-40f7-b633-6cb598c5bb26 Version: $LATEST
Received event: {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
value1 = value1
value2 = value2
value3 = value3
END RequestId: a334e3ba-27ec-40f7-b633-6cb598c5bb26

At the top of the log is the “Received event” print statement you uncommented from the code before saving the function. Then there’s the rest of the messages in the code. AWS sends standard output to CloudWatch logs for you. of course, you can direct these logs to Scalyr inside your code, or by importing your CloudWatch logs.

Let’s modify the code and run a different test.

First, uncomment the last line in the code and comment the line before it, so it looks like this:

import json

print('Loading function')

def lambda_handler(event, context):
    print("Received event: " + json.dumps(event, indent=2))
    print("value1 = " + event['key1'])
    print("value2 = " + event['key2'])
    print("value3 = " + event['key3'])
    #return event['key1']  # Echo back the first key value
    raise Exception('Something went wrong')

Now your code will raise an exception each time it’s called. Click the Save button on the top right-hand side of the page.

Next, rerun the test.

AWS caught the exception, logged it for you, and registered the test as a failure.

Congratulations! You wrote and tested your first AWS Lambda function.

 Success With AWS Lambda

Now that you can log in to AWS and create functions using Amazon’s blueprints, it’s time to take it to the next level. Start creating Lambdas with your code, and use them to tie your services together. Lambdas are a powerful mechanism for building scalable applications and a useful tool for coordinating activity between different services via events.

Stayed tuned for more posts about functions and serverless computing, and take a look at Scalyr’s tools for logging and log aggregation.

This post was written by Eric Goebelbecker. Eric has worked in the financial markets in New York City for 25 years, developing infrastructure for market data and financial information exchange (FIX) protocol networks. He loves to talk about what makes teams effective (or not so effective!)

Comments are closed.



Jump in with your own data. Free for 30 days.

Free Trial