DEV Community

Cover image for Cook a recipe with AWS: Simple and Easy Lambda Functions
Nandini Rajaram for AWS Community Builders

Posted on • Edited on

Cook a recipe with AWS: Simple and Easy Lambda Functions

Image description

AWS Lambda

AWS Lambda is a compute service. You can use it to run code without provisioning or managing servers.

Lambda function

The code you run on AWS Lambda is called a Lambda function
Lambda functions lack any ties to the underlying infrastructure and are stateless

Lambda supports the following languages:

  • Node.js
  • Python
  • Java
  • Go
  • C#
  • Ruby
  • PowerShell

Lets get started with AWS Lambda and cook some easy Lambda functions using Python

Ingredient

  • Python

Prerequisites

  • Log into AWS account with a valid user credentials (Root user not preferred)

Lets Jump to the Recipe

Author Lambda Functions in Python

Steps to create

  • Open the Lambda from the aws console

Image description

  • Click Create Function button

Image description

  • Choose Author from scratch option -Specify a Function name, I am going to create a function to print a Welcome message to the user. So my function name is going to be "Welcome_user"

Image description

  • Choose Python as your runtime. For me its Python 3.9 now and I am selecting it

Image description

  • Scroll down and now leave the rest of the settings to the default selections

Image description

By default, Lambda will create an execution role with permissions to upload logs to Amazon CloudWatch Logs

An IAM execution role defines the permissions that control what the function is allowed to do when interacting with other AWS services.

  • Create a new role with basic Lambda permissions will be selected by default
  • Now I will be able to see the following message "Lambda will create an execution role named Welcome_user-role-, with permission to upload logs to Amazon CloudWatch Logs"

Image description

  • Scroll down and Click Create Function button

Image description

  • Lets wait for couple of minutes to get navigated to the function page

  • Now on the function dashboard, there are several tabs Code, Test, Monitor, Configuration, Aliases, and Versions

Image description

  • We are now on the Code tab, down here we can see a lambda_function.py file.

Replace the code on the file with the below code

Image description

import json

def lambda_handler(event, context):
    message = 'Welcome {} {} to Cloud Tuner,  Get cloudified with AWS'.format(event['first_name'], event['last_name'])  

    #print to CloudWatch logs
    print(message)

    return { 
        'message' : message
    }
Enter fullscreen mode Exit fullscreen mode

The above function will print the welcome message with your name which you would pass through json while testing the code. The message will be also printed to the cloud watch logs

The return statement will return the value in the message variable

The Lambda function handler

  • The Lambda function handler is the method in your function code that processes events.
  • The handler method takes two objects – the event object(mandatory parameter) and context object (optional parameter)

    • event object: An object with information about the event that initiated the Lambda function
    • context object: This is generated by AWS and provides metadata about the action
  • Now Deploy the function by clicking on Deploy button

Image description

  • You should be able to see Changes Deployed once deployment completed

Now we have successfully deployed our code. Now its the time to test the code

Create a Test Event and Execute the Lambda Function

A test event is a JSON object that mocks the structure of requests emitted by AWS services to invoke a Lambda function. Use it to see the function’s invocation result.

Steps to create

  • Click the arrow next to the button Test

Image description

  • Click Configure test event

Image description

  • Lets create a new test event
  • Specify the Event name, I am going to name as "Welcome_user_test_event"

Image description

  • Replace the code on Event JSON with the below code

{
"first_name": "Ruby",
"last_name": "Jade"
}

Image description

  • Click Format JSON button to get the JSON code formatted
  • Now Click on Save button

Image description

  • We have created the Test Event successfully Lets Test the lambda code by clicking on the Test Button

Image description

And We can notice that execution results and the message getting printed "Welcome Ruby Jade to Cloud Tuner, Get cloudified with AWS"

You can also see Duration which is the execution time
Billed Duration is the time you are actually billed for

Image description

Before wrapping up, Remember, Lambda functions are short lived; the Lambda max timeout is 900 seconds (15 minutes)

Now, Lets verify if the CloudWatch has captured the Function Logs

Check Cloud Watch for the Function logs

Steps

  • Click on this Monitor tab.

Image description

This shows high-level CloudWatch metrics about our function with the details about number of invocations, duration, error count and success rate

  • To see detailed logs in Cloud Watch, Click View Logs in Cloud Watch

Image description

  • You will be navigated to cloud watch dashboard
  • You will be able to see detailed logs in Log stream

Image description

Image description

Some additional recipes

Try cooking Variety of Lambda Functions by following the above steps.
Below are the recipe for four different Lambda function along with JSON code which can be used to create Test Event to test them

Lambda Function to calculate the Square Root of a number

Function Name: SquareRoot
Function code

import json
import math
def lambda_handler(event, context):
    #to convert string to integer
    input =int(event['number'])
    squareroot = math.sqrt(input)
    message = 'The square root of the number {} is  {}! '.format(event['number'],squareroot)  

    #print to CloudWatch logs
    print(message)

    return { 
        'message' : message
    }

Enter fullscreen mode Exit fullscreen mode

Event JSON code
{
"number": 16
}

Lambda Function to calculate length of your name

Function Name: NameLength

Function code

import json
def lambda_handler(event, context):
    input = event['name']
    length_of_your_name= len(input)

    #print to CloudWatch logs
    print(input)
    print(length_of_your_name)

    return { 
        'input' : input,
        'length_of_your_name':length_of_your_name

    }
Enter fullscreen mode Exit fullscreen mode

Event JSON code
{
"name": "Tuner"
}

Lambda Function to search a word on the input string

Function Name: SearchString
Function code

import json

def lambda_handler(event, context):
    input=event['input_string']
    key=event['word_to_be_searched']
    isPresent=key in input
    message = 'The presence of  {} in  {} is {} '.format(key,input,isPresent)  

    #print to CloudWatch logs
    print(message)

    return { 
        'message' : message
    }
Enter fullscreen mode Exit fullscreen mode

Event JSON code
{
"input_string": "Stay tuned with Cloud Tuner and get cloudified with AWS",
"word_to_be_searched": "AWS"
}

Lambda Function to reverse the input string

Function Name: ReverseString
Function code

import json

def lambda_handler(event, context):
    input= event['first_name']
    reversed_string = event['first_name'][::-1]
    print(reversed_string)
    #print to CloudWatch logs


    return { 
        'input':input,
        'reversed_string' : reversed_string
    }

Enter fullscreen mode Exit fullscreen mode

Event JSON code
{
"first_name": "cloud"
}

Thank You

Top comments (2)

Collapse
 
smgit profile image
SM

Nice article 👌

Collapse
 
vijay_21 profile image
Vijay Ramanathan

Nice👌🏻