AWS Lambda Quick Start Guide

By Markus Klems
    Advance your knowledge in tech with a Packt subscription

  • Instant online access to over 7,500+ books and videos
  • Constantly updated with 100+ new titles each month
  • Breadth and depth in over 1,000+ technologies

About this book

AWS Lambda is a part of AWS that lets you run your code without provisioning or managing servers. This enables you to deploy applications and backend services that operate with no upfront cost. This book gets you up to speed on how to build scalable systems and deploy serverless applications with AWS Lambda.

The book starts with the fundamental concepts of AWS Lambda, and then teaches you how to combine your applications with other AWS services, such as AmazonAPI Gateway and DynamoDB. This book will also give a quick walk through on how to use the Serverless Framework to build larger applications that can structure code or autogenerate boilerplate code that can be used to get started quickly for increased productivity.

Toward the end of the book, you will learn how to write, run, and test Lambda functions using Node.js, Java, Python, and C#.

Publication date:
June 2018
Publisher
Packt
Pages
184
ISBN
9781789340198

 

Getting Started with AWS

Amazon Web Services (AWS) is a collection of web services that together make up a cloud computing platform that can help make an organization more efficient. It offers a broad set of global computing, storage, database, analytic, application, and deployment services. AWS is very beneficial as it is highly flexible and very easy to use. It is also very cost-effective and reliable, with high performance and scalability.

In this chapter, we are going to take a look at fundamental AWS concepts, such as cloud service usage and pricing models. We will explore the AWS web dashboard, the so-called Management Console. On the Management Console, we will take our first steps with Lambda and the API Gateway Service.

Now, we are going to have a look at the following topics:

  • Introduction to the fundamental concepts of AWS
  • AWS account walkthrough
  • AWS Lambda
  • AWS API Gateway
 

Installation and setup guide

Before going any further into how to use AWS, let's first create and set up an AWS account. This is a prerequisite for getting started with programming AWS Lambda. Here, I'm going to show you how to sign up for an AWS account and then I will show you how to create a special IAM user with administrator access permissions. After that, I'll show you how to set up a local development environment with AWS credentials. So let's dive in:

  1. First, open the web browser on the main website of Amazon Web Services, https://aws.amazon.com/
  2. Click on the Create an AWS Account button to create a new AWS account
  3. Select the I am a new user radio button and enter your email address
  4. Then, fill out the rest of the information and go through the sign-up process:

Once the account has been created, sign in to the AWS Management Console. More information on the console will be provided later on. For now, click Services in the drop-down menu and search for IAM. Click on IAM to navigate to the Identity and Access Management dashboard. Here, I am going to show you how to create a special IAM user that has certain permissions to use AWS services on my behalf. This is a good security practice. You shouldn't use your root account credentials for programmatically accessing Amazon Web Services. It could create problems for you—for example, you could accidentally publish your AWS credentials on GitHub or somewhere else where other people can see them, and using these details, they could then use your AWS services. If this happens to you, it's pretty easy to use IAM to simply delete your user and revoke these permissions:

In this tutorial, I'm going to create a group and an IAM user to perform the exercises. After we are done with the tutorial, you can simply delete the user and the group.

Let's start by creating an IAM group. Set up a group name. For this tutorial, I am naming the group learninggroup. For simplicity, what I'm going to do is give my group administrator access. If you're more paranoid, you can restrict this further, but then you might have to deal with a bit more hassle. I think for the purposes of this tutorial, and assuming that you will delete this group and the user later on, it's fine to go with administrator access. Click on Next Step and Create Group.

Now I'm going to create a new user. Click on Users | Add User. Here, I will give my user the name learninglambda, and I'm going to select the programmatic access checkbox. This will create an access key ID and a secret access key so that you can programmatically use Amazon Web Services:

In the next step, I will show you how to set up your local development environment with the access key ID and the secret access key ID so that you can use AWS from within IDEs, such as Eclipse or Visual Studio, or through development frameworks, such as the Serverless framework. If you want, you could also give your new IAM user AWS Management Console access. Click on Next Permissions. I added my IAM user to the learninggroup and now I'm going to create the user. Once the user has been created, you will be provided with the access key ID and the secret access key ID. Copy both of them into a blank text file as you will need them for the next step. Copy both of them into a text editor:

AKIAIWRW3LZDPQIY3TPQ
v9kIjVVCd0pDWTB0LJDKtVi3+MVlYhkDlyBF79z7

Now, I'm going to show you how to set up your local development environment so that you can programmatically access AWS services from within your local development environment. This is used by a number of IDEs, such as Eclipse or Visual Studio, and other development frameworks, such as the Serverless framework. I'm going to show you how to do this for macOS. It works in a similar way for Linux.

So the first thing that we need to do is create a hidden directory named AWS in your home folder. I created a hidden directory, and now in that directory I will create a file named credentials. In that file, I'm going copy my access key and my secret access key in the following format. What this does is specify the IAM profile that I want to use:

mkdir ~/.aws
touch ~/.aws/credentials

This is the default IAM profile that my IDE or development framework is going to use with the following access key ID and secret access key credentials. After you have entered the content into your credentials file, it should look like the following:

[default]
aws_access_key_id=AKIAISSXZB2PNT6VVG3Q
aws_secret_access_key=ybv3rDoNNJDdbF0l9XWxVaHv0t8bYF5p0hU5g

You need to set up your own access key ID and secret access key, because the credentials that we have been using will soon not exist anymore:

cat ~/.aws/credentials

Now I am going to explain how to set up your AWS credentials file on your operating system.

Set up your local development PC/laptop with AWS credentials

If you are using Linux or macOS, you should create a hidden directory, .aws, in your home folder. If you're using Windows, you should create a hidden AWS directory in your user's profile directory. Then you copy the content, your access key ID, and the secret access key.

Installing the Serverless framework

To install the Serverless framework, you basically need to do the following:

  • You need to install Node.js. When you install Node.js, the Node package manager will be installed.
  • Then you can use npm, the Node package manager, to install the Serverless framework by typing npm install -g. This will initiate a global installation so you can launch the serverless command from anywhere on Terminal. Type npm install -g serverless into Terminal to install the Serverless framework using the node package manager.
 

Introduction to AWS

Let's move on to the first official section of this chapter, which gives you an introduction to AWS. In this section, we are going to take a look at Lambda usage and pay-per-use pricing, and also where to find documentation and other developer resources:

  1. Let's go to the home page for aws.Amazon.com/lambda, as shown in the following screenshot:
  1. Head over to the Documentation page. The Documentation page gives you links to many useful resources, such as SDKs and tools. But, for now, let's take a look at the Developer Guide.
  2. The Developer Guide gives us a lot of useful background information on how Lambda works.
  1. Click on the section called Building Applications with AWS and click on the Event Source Mapping:
  1. Scroll down a bit and you will be able to see an example of how we can use Lambda, shown in the following screenshot:

In this example, Amazon S3 pushes events and invokes a Lambda function. Amazon S3 (or Amazon Simple Storage Service) is a scalable web service for storing and retrieving large amounts of data. In this example, we have a user who uploads a file into an Amazon S3 bucket. This triggers an object-created event. The object-created event is detected by Amazon S3, which triggers S3 to invoke our Lambda function. The Lambda function is associated with an execution role. The execution role gives our set certain permissions. So, in this scenario, Amazon S3 needs to have permissions to invoke our Lambda function, otherwise any other service would be able to invoke our Lambda function, which we want to avoid. So, if these permissions are given, our Lambda function is invoked with the event data from our Amazon S3 service invocation. This is also referred to as the push event model, but there's another way to use AWS Lambda. Let's scroll down a little bit to the next example:

Here, we have a stream-based service. In this example, Lambda pulls events from an Amazon Kinesis stream and invokes the Lambda function. On the left-hand side, you can see a custom application that writes data on a Kinesis stream. On the right-hand side, our Lambda function continuously picks up pieces or records from this stream. Again, we have an execution role associated with our Lambda function, but in this case it works the other way around. In this case, we need to give our Lambda function permission to access the Kinesis stream because here we are in the so-called pull event model. Whenever we pick up a new record, the Lambda function is executed.

Cloud service pricing

Now let's take a quick look at cloud service pricing. Cloud services work quite differently from traditional web hosting, and this also applies to pricing. With the traditional web hoster, you typically sign up for a long-term contract, maybe one year or two years, and you pay for the resources whether you use them or not. With cloud services, this works quite differently. With cloud services, you only pay for the resources that you actually use with very fine granularity. The downside of this is that the pricing model becomes a bit more complicated:

As you can see in the preceding screenshot, each Amazon web service has its individual pricing model. Typically, it breaks down into charges for the compute capacity, storage capacity, and data transfer that you use.

Let's take a closer look at the pricing model of AWS Lambda. The pricing model breaks down into two parts:

  • First, you pay for requests, which is actually quite cheap. It's only 20 cents for 1 million requests.
  • The other thing that you pay for is duration, which is the time that your Lambda function runs for. This time period is rounded up to the nearest 100 milliseconds. So, if you have a short-running Lambda function that only runs for 50 milliseconds, you pay for 100. If you have a Lambda function that runs for 910 milliseconds, you pay for 1 full second. You also have to pay for the amount of memory that you allocate to your function. You can configure your Lambda function with different levels of memory. You then get charged this fixed price, price constant, for every gigabyte-second that you use.

Let's take a quick look at a sample calculation. When you scroll further down in the page, you will see different pricing examples. Let's have a look at the first pricing example.

Pricing example

In this example, you will configure your Lambda function with half a gigabyte of memory. We will assume that the Lambda function is called 3 million times within one month. Each Lambda function, we will assume, runs for one second. With this in mind, our monthly compute charges would be calculated as follows:

Given these details, we need to calculate the total amount of time that our Lambda function is running for: 3 million invocations X one second per invocation is equal to 3 million seconds. Then we calculate the compute capacity that is used during these invocations. We use Lambda functions for 3 million seconds, and each Lambda function is allocated with half a gigabyte of memory, so we use 1.5 gigabyte-seconds. However, Lambda comes with a free tier, so up to a certain level you get compute capacity and requests for free. So if you deduct these from your calculation, then you end up with 1.1 gigabyte-seconds. To calculate this, you multiply that with your fixed price constant and you end up with roughly 18 dollars per month:

You must also pay for request charges. However, this only costs 20 cents per million requests, and the first million requests are free, so you only have to pay for 2 million requests, which in other words will cost you only 40 cents.

So your final calculation for the monthly charges will amount to roughly 18-19 dollars per month (both the compute and request charges).

The next section is about the AWS web dashboard, the so-called Management Console. So let's dive into that!

 

AWS Management Console

After reading the previous section, you will be familiar with Lambda usage and pricing models. Now we are going to explore the AWS Management Console.

In this section, we are going to take a look at how to navigate the Management Console, how to switch between services, and what Amazon Web Service regions are. Get onto the landing page of AWS, aws.amazon.com. Sign in to the Management Console by clicking on the button in the upper-right corner. Once signed in, you will see a navigation bar on the top. On the left-hand side, there's a Services dropdown. You can see all the Amazon Web Services that are available to us, as shown in the following screenshot:

These services are all clustered by service category; for example, compute services such as EC2-Lambda are also in this category. We also have storage services, such as S3, the simple storage service. We also have database services, such as DynamoDB, a database service that we will use later. Finally, there are also application services, such as API Gateway. You can also pin certain services to your navigation bar to access them more quickly. Click on the little pin button and you can drag down a service or drag up a certain service. Click the little pin button again; now it's stuck to your navigation bar.

Regions

One concept that is important to know about is the concept of regions. I'm currently in the North Virginia, or US East 1, region. This is the default region for all Amazon Web Services. If I click on this drop-down menu, I can see other regions, such as Ohio, Northern California, Ireland, Frankfurt, and so on. Each region corresponds to an Amazon Web Services data center, and most services are specific to a certain region, so if you create resources, they are bound to the particular region that they were created in. If you switch region, you won't see resources that you created in another region. Moreover, not all services are available in all regions. If we click, for example, on Lambda, then we can see that Lambda is available in Northern Virginia, but it is not available in Canada Central, in Asia Pacific Mumbai, or in South America, at least not at the time of writing. So it will typically take some time before all regions catch up and support all services. In this tutorial, I will use the EU Frankfurt region, and I would advise that you use the same region so that what I show you is consistent with what you are doing.

So if you use a service in a certain region, it typically has a region-specific endpoint. You can find more information about regions and endpoints at docs.aws.amazon.com/general/latest/gr/rande.html.

The following screenshot shows regions where Lambda is available:

In the next section, we are going to create our first Lambda function. Let's get on with that!

 

AWS Lambda

In the previous section, we learned about the Amazon Web Service Management Console. Now we will look into AWS Lambda. Here, we are going to take a look at the Lambda web dashboard, the Lambda function blueprints, how to configure and deploy the Lambda function, and how to test it—all from the Management Console. So let's head over to the Lambda service.

To learn how to access the Lambda service, read the AWS Management Console section.

Once you are in your Lambda web dashboard, click on the blue Get Started Now button to create your first function.

You can select from a number of blueprints, which give you Lambda functions with a little bit of dummy code. You can filter by runtime, and since this is volume one, we want to use Node.js. So click on Node.js 4.3:

Let's use the Blank Function blueprint. If I want, I can create a trigger that triggers my Lambda function. There are different kinds of triggers, but for the first exercise, let's not select any trigger. Let's leave it empty and just click on the Next button.

Now we need to enter some configuration information for our function, such as a function name:

The runtime is correct, so we will scroll down a little bit. Here you can see that I have a function handler, as shown in the highlighted portion in the following code:

exports.handler = (event, context, callback) => {
// TODO implement
callback(null, 'Hello from Lamda');
};

This function will be assigned to the exports.handler property, which is then exported through the Node.js export. My Lambda function handler takes up to three arguments. The last argument, the callback, is optional. The first argument is my event, so my Lambda function; is triggered through an event. The caller of my Lambda function can pass in information. For example, if an S3 object-created event invokes my Lambda function, I can retrieve object metadata. If an HTTP request invokes my Lambda function, I can retrieve, for example, a JSON body from the HTTP event. The second object is the context of my Lambda function, I can access runtime information through this context object. Last but not least, the optional callback function is the typical Node.js error-first callback function. I can invoke it in this case without an error, so I will set the first parameter, or the first argument, to null. I also set the result, the second argument, to Hello from Lambda. So the caller will retrieve the message Hello from Lambda when the Lambda function is invoked.

What we also need to do is set the right permissions for the Lambda function. So scroll down to the Lambda function handler and role. Click on the Role dropdown, and create a custom role. Select lambda_basic_execution in the IAM Role dropdown and click on Allow. This will set the role to Lambda basic execution, as shown in the following screenshot:

You can even configure the amount of memory that you want to use in your Lambda function by scrolling down. Remember, the more memory you give it, the faster it executes, but the more you have to pay. Let's stick to the smallest amount, 128 megabytes. You can also specify a timeout so that if the Lambda function doesn't terminate within this amount of time, then it times out. Let's leave it at the default of three seconds.

Scroll down and click on the Next button. Have a look at the settings, scroll down, and click on Create Function. You will be able to obtain similar details to those shown in the following screenshot:

Congrats! You have created your first Lambda function! Let's test it.

Click on the Test button and this will execute the test that results in Lambda saying Hello.

You can also configure your test event in this way and give it sample event data. Since I don't use the event in my simple Lambda function at all, it doesn't matter what is pasted—simply click Save and Test.
 

AWS API Gateway

In the previous section, we created our first Lambda function. Now let's explore the API Gateway Service. Let's take a look at the API Gateway Service web dashboard. We will use it to create a new API and then connect that API to our Lambda function. Last but not least, we will test our API, and through our API, we will invoke the Lambda function. So let's start.

Log in to the Management Console in the Frankfurt region where you can create your first Lambda function. Now let's go to the API Gateway Service. If you don't have an API gateway, click on Let's Get Started. Amazon might ask you to import an API. Import it, and once done, you will be able to see a reference API that can be used to learn more about APIs, but it will be a bit too complex for our first use case. So, let's create a simpler API by clicking on the Create API button. Create a new API and give it the name FirstAPI. After that, click on Create API.

So now I have an API, and it can configure a couple of things, but for now, let's just create a resource that can be found in the Actions button, as shown in the following screenshot:

I will take a REST resource and name it foo. It will get the resource path foo. After this, I will click on Create Resource. A resource alone is not enough; I also need a method. So let's click on Create method and select an HTTP GET method, as seen in the following screenshot:

Click on the little checkmark. Et voila! We have a simple API with one resource, foo, and a GET method:

Now we can integrate it with different kinds of services. We want to integrate it with our Lambda function, so the first radio button is correct. We select the region. In our current example, we are in the Frankfurt region and our Lambda function is also in the Frankfurt region, so select eu-central-1, which is the Frankfurt region, and then type in the Lambda function name. I gave it the name firstLambda. Click on Save.

Now the API gateway will ask you if you give the API gateway permission to invoke your Lambda function:

So remember from the beginning that you need to give your API permission to invoke your Lambda function; otherwise, just anyone can invoke your Lambda function, which you don't want. Click on OK.

Now, we have created an integration between our API and our Lambda function. Let's click on the little Test button, as shown in the following screenshot:

Once you click it, you will be able to execute an HTTP GET request by scrolling down the page and clicking on the TEST button.

Within 90 milliseconds, we will get a response back—Hello from Lambda, as seen in the following screenshot:

So it looks like we really invoked our Lambda function, but can we be sure? Let's check. Go back, and click on the foo resource and then click on the GET method. Now we can see our integration again, and on the right-hand side, you can see the Lambda function that I have integrated my API with. Click on it and you will be directed to the Lambda dashboard with your Lambda function. Let's take a look at the Monitoring tab:

As you can see, it has in fact just been invoked—a couple of times, actually.

 

Summary

In this chapter, we learned a couple of things: how to navigate the AWS web dashboard, and how to navigate the Management Console. We also created and tested our first Lambda function and then we created a REST API and connected it to Lambda. Then we invoked the API, and through the API, we invoked our Lambda function. As you can imagine, it can become quite tedious to create more complex applications if we do it all on the Management Console. The Management Console is great for getting started, but it's not the right tool for building serious applications. It would be great if there was a programmatic framework that would help us to do that. Thankfully, there is. In the next chapter, we will explore the Serverless framework, which is a development framework that helps you to build serverless applications. See you there.

About the Author

  • Markus Klems

    Markus Klems is a software development and system administration expert for scalable, high-availability, and high-performance software systems, such as big data, mobile, web application, and Software-as-a-Service systems. Within the framework of his research and development work at TU Berlin and Karlsruhe Institute of Technology (KIT), Markus has gained in-depth knowledge and experience of complex and large-scale IT systems. He has been working with Amazon Web Services (AWS) since 2008 and is particularly excited about serverless computing and serverless microservice architectures.

    Browse publications by this author
Book Title
Unlock this book and the full library for FREE
Start free trial