• Classes
  • 07 - Lambda Functions
  • Part 1

AWS Lambda - Practicing

Let's create our own function in AWS Lambda.

Create Folder

Question 1

Create a new folder and store all the source code in it!

Create .env

Question 2

Create an .env file containing the variables:

AWS_PROFILE="mlops"
AWS_REGION="us-east-2"
AWS_LAMBDA_ROLE_ARN="arn:xxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

Tip! 1

You will fill ARN variable in just a moment!

Create AWS Role

A Lambda function needs permissions to execute. To provide these permissions, we need to create an AWS Role and attach the necessary policies to it.

Creata a file trust-policy-basic.json with the following content:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": "lambda.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

Then, run the following code to create the role and attach the necessary policies:

$ aws iam create-role --role-name mlops-role-basic-lambda --assume-role-policy-document file://trust-policy-basic.json --profile mlops --region us-east-2
$ aws iam attach-role-policy --role-name mlops-role-basic-lambda --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole --profile mlops

Now, you can get the role ARN with the following command:

$ aws iam get-role --role-name mlops-role-basic-lambda --query 'Role.Arn' --output text --profile mlops

Question 3

Copy the returned ARN and paste it in the AWS_LAMBDA_ROLE_ARN variable in your .env file.

Create function

Question 4

Create a file called my_lambda.py containing the function that will run on AWS.

For now, we'll make a simple function that responds with a fixed JSON!

Source code:

def say_hello(event, context):
    return {
        "created_by": "your name",
        "message": "Hello World!"
    }

Tip! 2

The function say_hello will be our handler function.

Create ZIP

Question 5

Create a file called my_lambda.zip that is the compression my_lambda.py.

Show functions

Let's use this code to list the functions available in our account:

import boto3
import os
from dotenv import load_dotenv

load_dotenv()

# Create a Boto3 client for AWS Lambda
session = boto3.Session(
    profile_name=os.getenv("AWS_PROFILE"), region_name=os.getenv("AWS_REGION")
)

lambda_client = session.client("lambda")


# Call the list_functions API to retrieve all Lambda functions
response = lambda_client.list_functions(MaxItems=1000)

# Extract the list of Lambda functions from the response
functions = response["Functions"]

print(f"You have {len(functions)} Lambda functions")


# Print the name of each Lambda function
if len(functions) > 0:
    print("Here are their names:")

for function in functions:
    function_name = function["FunctionName"]
    print(function_name)

If you have many functions, you may need to paginate through the results:

import boto3
import os
from dotenv import load_dotenv

load_dotenv(override=True)

# Create a Boto3 client for AWS Lambda
session = boto3.Session(
    profile_name=os.getenv("AWS_PROFILE"), region_name=os.getenv("AWS_REGION")
)

lambda_client = session.client("lambda")

# List all Lambda functions with pagination
functions = []
next_marker = None

while True:
    if next_marker:
        response = lambda_client.list_functions(Marker=next_marker)
    else:
        response = lambda_client.list_functions()

    functions.extend(response["Functions"])

    # Check if there are more functions to fetch
    next_marker = response.get("NextMarker")
    if not next_marker:
        break

print(f"You have {len(functions)} Lambda functions")

# Print the name of each Lambda function
if functions:
    print("Here are their names:")

for function in functions:
    function_name = function["FunctionName"]
    print(function_name)

Question 6

Run the Python code and check out the functions currently available in our account!

Create Lambda Function

Let's create a lambda function with:

Atention!

Change the function_name variable.

Provide a name in the pattern sayHello_<YOUR_INSPER_USERNAME>

import boto3
import os
from dotenv import load_dotenv

load_dotenv()

# Provide function name: sayHello_<YOUR_INSPER_USERNAME>
function_name = ""

# Create a Boto3 client for AWS Lambda
session = boto3.Session(
    profile_name=os.getenv("AWS_PROFILE"), region_name=os.getenv("AWS_REGION")
)

lambda_client = session.client("lambda")

# Lambda basic execution role
lambda_role_arn = os.getenv("AWS_LAMBDA_ROLE_ARN")

# Read the contents of the zip file that you want to deploy
# Inside the "my_lambda.zip" there is a "my_lambda.py" file with the
# "say_hello" function code
with open("my_lambda.zip", "rb") as f:
    zip_to_deploy = f.read()

lambda_response = lambda_client.create_function(
    FunctionName=function_name,
    Runtime="python3.12",
    Role=lambda_role_arn,
    Handler="my_lambda.say_hello", # Python file DOT handler function
    Code={"ZipFile": zip_to_deploy},
)

print("Function ARN:", lambda_response["FunctionArn"])
Tip: How to delete Lambda function

If you want to delete a function, you can use the following code:

import boto3
import os
from dotenv import load_dotenv

load_dotenv(override=True)

# Provide function name, e.g. sayHello_<YOUR_INSPER_USERNAME>
function_name = ""

if len(function_name) == 0:
    raise ValueError("No function name provided!")

# Create a Boto3 client for AWS Lambda
session = boto3.Session(
    profile_name=os.getenv("AWS_PROFILE"), region_name=os.getenv("AWS_REGION")
)

lambda_client = session.client("lambda")

try:
    response = lambda_client.delete_function(FunctionName=function_name)
    print(f"Lambda function '{function_name}' deleted successfully!")
except lambda_client.exceptions.ResourceNotFoundException:
    print(f"Lambda function '{function_name}' not found.")
except Exception as e:
    print("Error while deleting Lambda function:", str(e))

Question 7

Run the Python code to create the function. Then write down the returned ARN

Question 8

Rerun the code to display the existing functions in the account.

Check that your function was created correctly.

Check if worked

Let's check if the function worked:

Atention!

Change the function_name variable.

import boto3
import os
import io
from dotenv import load_dotenv

load_dotenv()

# Create a Boto3 client for AWS Lambda
session = boto3.Session(
    profile_name=os.getenv("AWS_PROFILE"), region_name=os.getenv("AWS_REGION")
)

lambda_client = session.client("lambda")

# Lambda function name
# Provide function name: sayHello_<YOUR_INSPER_USERNAME>
function_name = ""

try:
    # Invoke the function
    response = lambda_client.invoke(
        FunctionName=function_name,
        InvocationType="RequestResponse",
    )

    payload = response["Payload"]

    txt = io.BytesIO(payload.read()).read().decode("utf-8")
    print(f"Response:\n{txt}")

except Exception as e:
    print(e)

Question 9

Make sure the function returns the expected result

This code provides a way to check if the lambda function works. However, when integrating it with other applications, its execution would probably depend on an event such as the creation of a file on S3 or an API call.

Let's check out how to use API Gateway to create an API for our Lambda function.