How to Create Your First Lambda Function on AWS

Reading Time: 5 minutes

In the beginning, the documentation for AWS LAMBDAS can be intimidating at times, but don’t worry, in this post, I will help you with the first steps to create an AWS LAMBDA Function. Keep reading!

 

What’s a Lambda Function?​

Amazon Web Services (AWS) Lambda is a compute service that lets you run code without provisioning or managing servers.

AWS Lambda is a compute service that lets you run code without provisioning or managing servers. Share on X

Also, AWS Lambda can be used to run your code in response to events, such as:

  • Changes to data in an Amazon S3 bucket or an Amazon DynamoDB table;
  • Running your code in response to HTTP requests using Amazon API Gateway, or invoke your code using API calls made with AWS Software Development Kits (SDKs).
  • Among others.

Let’s get the coding started

Assuming that you already have an AWS account, now is the time to create a new Lambda Function:

Screen Shot 2020-06-30 at 16 38 20

AWS Lambda is different from a traditional approach based on physical or virtual servers. You only need to give your logic, grouped in functions, and the service itself takes care of executing the functions. Share on X

After that, search for Lambda into the Find Services field:

Screen Shot 2020-06-30 at 16 39 08


Then, click on Create function

Screen Shot 2020-06-30 at 16 40 21

At this moment, as you can see, we have three options to create a Lambda Function:

Screen Shot 2020-06-30 at 16 42 26


Author from scratch:

This option starts with a simple Hello World example.

Use a blueprint:

This one allows you to build a Lambda application from sample code and configuration presets for common use cases.

Browse serverless app repository:

And, this one permits you to deploy a sample Lambda application from the AWS Serverless Application Repository.​

For the example in this blog post, we will use the first option, Author from scratch:

To start. set the Function name and the programing language of your preference. In this case; we will use Python on its latest version 3.8.

Screen Shot 2020-06-30 at 16 42 03

To illustrate this, we will use this example code to return our AWS Account Settings:​

#!/usr/bin/python
​
import os
import logging
import jsonpickle
import boto3
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch_all
​
logger = logging.getLogger()
logger.setLevel(logging.INFO)
patch_all()
​
client = boto3.client('lambda')
​
def lambda_handler(event, context):
logger.info('## ENVIRONMENT VARIABLES\r' + jsonpickle.encode(dict(**os.environ)))
logger.info('## EVENT\r' + jsonpickle.encode(event))
logger.info('## CONTEXT\r' + jsonpickle.encode(context))
response = client.get_account_settings()
​
return response

Screen Shot 2020-06-30 at 16 50 10


Screen Shot 2020-06-30 at 17 52 28

If you want to test the Lambda Function, click on the Test button and you will be able to create a new Event.

Screen Shot 2020-06-30 at 16 55 08


After that, we will be able to test our function. So, let’s get to work:

Screen Shot 2020-06-30 at 18 08 55


Oh, no! That’s an error! But, don’t worry, we can check what is causing it, and then solve it:

Screen Shot 2020-06-30 at 16 55 29

{
"errorMessage": "Unable to import module 'lambda_function': No module named 'jsonpickle'",
"errorType": "Runtime.ImportModuleError" 
}


This is a very common error when working with Lambda Functions. This means that we need to import the necessary libraries to our lambda function, and for that, we need to do the following:

Installing AWS CLI

For MacOS:

$ brew install awscli

If you would like to do it manually, do it this way:

$ curl "https://awscli.amazonaws.com/AWSCLIV2.pkg" -o "AWSCLIV2.pkg"
$ sudo installer -pkg AWSCLIV2.pkg -target /

If you use Linux, you can try this way:

$ curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
$ unzip awscliv2.zip
$ sudo ./aws/install

Updating a function with additional dependencies

Then, for connecting with your AWS you need to:

Create your Lambda folder, following the same structure as the AWS:

- myFirstFunction
- lambda_function.py


Inside your Lambda folder, create a new folder called package:

~/lambda-project$ mkdir package/


Create a zip file (this will be uploaded after):

~/lambda-project$ zip function.zip lambda_function.py

Then, ​install the necessary dependencies:

~/lambda-project$ pip install --target ./package jsonpickle boto3 aws_xray_sdk
Collecting jsonpickle
Using cached https://files.pythonhosted.org/packages/af/ca/4fee219cc4113a5635e348ad951cf8a2e47fed2e3342312493f5b73d0007/jsonpickle-1.4.1-py2.py3-none-any.whl
Collecting boto3
Downloading https://files.pythonhosted.org/packages/b4/63/2814ea50d805b449554dd101df0b6ee9f23061157fc1f3c6d1202f4a9b85/boto3-1.14.14-py2.py3-none-any.whl (128kB)
|████████████████████████████████| 133kB 551kB/s
Collecting aws_xray_sdk
Downloading https://files.pythonhosted.org/packages/e1/cd/12f2bc3a7683e88abe60ee6e0c09248103052b7532a7cf7ce1fccefa1a71/aws_xray_sdk-2.6.0-py2.py3-none-any.whl (94kB)
|████████████████████████████████| 102kB 5.1MB/s
Collecting importlib-metadata (from jsonpickle)
Using cached https://files.pythonhosted.org/packages/8e/58/cdea07eb51fc2b906db0968a94700866fc46249bdc75cac23f9d13168929/importlib_metadata-1.7.0-py2.py3-none-any.whl


After that, add it to the zip file that you created previously:

~/lambda-project$ cd package
~/lambda-project/package$ zip -r9 ${OLDPWD}/function.zip .
adding: aws_xray_sdk-2.6.0.dist-info/ (stored 0%)
adding: aws_xray_sdk-2.6.0.dist-info/RECORD (deflated 71%)
adding: aws_xray_sdk-2.6.0.dist-info/LICENSE (deflated 65%)
adding: aws_xray_sdk-2.6.0.dist-info/WHEEL (deflated 14%)
adding: aws_xray_sdk-2.6.0.dist-info/top_level.txt (stored 0%)
adding: aws_xray_sdk-2.6.0.dist-info/INSTALLER (stored 0%)
adding: aws_xray_sdk-2.6.0.dist-info/METADATA (deflated 69%)
adding: s3transfer/ (stored 0%)
adding: s3transfer/delete.py (deflated 63%)
adding: s3transfer/tasks.py (deflated 72%)
adding: s3transfer/compat.py (deflated 59%)
adding: s3transfer/upload.py (deflated 78%)
adding: s3transfer/download.py (deflated 77%)

Then, add an empty __init__.py file at the same level of your lambda_function.py
touch __init__.py

You have to do this because some of the necessary dependencies need that file to consider it as a valid Python package. Look at the example:

Link to example.

As you can see in there, you have to add it to your zip file:

~/lambda-project$ zip function.zip __init__.py


And then, update your Lambda Function:

~/lambda-project$ aws lambda update-function-code --function-name myFirstFunction --zip-file fileb://function.zip
{
"FunctionName": "myFirstFunction",
"FunctionArn": "arn:aws:lambda:us-east-2:120743116205:function:myFirstFunction",
"Runtime": "python3.8",
"Role": "arn:aws:iam::120743116205:role/lambda-execution-stitch",
"Handler": "lambda_function.lambda_handler",
"CodeSize": 10394470,
"Description": "",
"Timeout": 3,
"MemorySize": 128,
"LastModified": "2020-06-30T22:16:10.317+0000",
"CodeSha256": "RmdV/Zu68GzjOdgJREZynVTk1nvKNDgNjXdcK+/tWNo=",
"Version": "$LATEST",
"TracingConfig": {
"Mode": "PassThrough"
},
"RevisionId": "e529323a-6c87-4e41-ac7f-42ab6a947a6c",
"State": "Active",
"LastUpdateStatus": "Successful"
}


Now, it’s time to run our Lambda Function again!:

{
"AccountLimit": {
"CodeSizeUnzipped": number,
"CodeSizeZipped": number,
"ConcurrentExecutions": number,
"TotalCodeSize": number,
"UnreservedConcurrentExecutions": number
},
"AccountUsage": {
"FunctionCount": number,
"TotalCodeSize": number
}
}


Hurray! We finished. Now everything is working ok and we get a successful response:

Screen Shot 2020-06-30 at 17 47 04

Wrap Up

Consider this as an introduction to Lambda functions. In the beginning, when you start digging into the AWS ecosystem, it can be scary. But don’t worry. I made this blog post to help you take the first step, hoping that in the future, you can create Serverless applications and solve different kinds of problems.

Thank you for reading this post. Please let me know if you have any questions. I’ll be glad to answer them.

 
@JhonatanTapia, Senior Software Engineer at MagmaLabs

0 Shares:
You May Also Like