-->

17/08/2019

AWS Lambda Function - How to Create - Test - Run

We are not going to talk about how AWS Lambda are server less and how usefull they are or where does Lambda functions fit in your solutions.
AWS Documentation is there to explain way better than i do. Here is the Link.

We are here to 
1. Create IAM User, assign permissions
2. Create your first Lambda function. 
3. Understand the code.
4. Test the code.
5. Access and Execute Lambda function from AWS CLI
6. Understand how to pass parameters when calling Lambda function.
7. Error Handling and Logging.

Lets keep the code simple to maximize understanding of concept behind.


First you need to have a AWS free-tier registration. using which you get access to lot of functionality in limited quantities for 12 months for free. Here is the link to find what you get for free every month.

I assume you have access to free-tier memebership and you can log onto your management console.

So lets begin by creating out first Lambda Function. 

Step 1: Create IAM User, assign permissions

Its recommended to create a IAM user and assign permissions before doing anything is AWS.

Go to AWS Management Console => Services => IAM => Users on the left pane.

Click "Add User" button. I am naming this user "LambdaUser".
Please check enable Programatic Access by enabling Access Key and Secret.
In next step we assign reasonable permissions to the user. Use "Attach Existing Policy" ad search for LambdaExecute. This is what you choose in reality.

But for ease of execution as this is your first demo, select Adminstartor Access. Select poilcy from list and finish creating the user. This way you dont need to deepdive in to IAM if permsisions are not sufficient.


After review you will be taken to a screen where User Access Key and secret were shown. Copy and paste it in a notepad for further reference.
We are done creating users with required permissions.

Step 2: Create your first Lambda function. 

Please make a note of which reagion you are using. For now choose Oregon.
Go to AWS Management Console => Services => Lambda => Either "Get Started" or "Create Function" 
Choose "Create from Scratch", Name you function. I choose Python for its simplicity and trust me though it supports C#, Java; Python makes life easy coming to automation and other stuff.
Select "Create a new Role with required permissions" option.
Now you can see a Lambda Config page where you can modify the Lamda function.
Select Configuration tab on which you see designer for Lambda. Click on "MyFirstLambda", name of the lambda function. Scroll down and you see the code editor. Paste below code.

import json

def lambda_handler(event, context):

    input=event["input"]
    return {
        'statusCode': 200,
        'body': json.dumps('Hello '+input+', Welcome to AWS Lambda')
    }

and click Save on the top of the page.

Step 3: Understand the code.

In here there are 3 things you need to learn
1. lambda_handler() is the method which handles the calls to this function.
2. event parameter gives the details of the payload or JSON you sent as a parameter to the function.
3. context paramter gives you all the contenxtual information like requestid, ARN for the function, a method to tell how much time to finish executing and so on.

Now if you look at our code, we are taking input key from event parameter and give a output with welcome message embedding the user name.

 Step 4: Test the code.

Now we need to unit test the code and see the out come. For that on top of the page you see a dropdown beside "Test" button. select "Configure test events" option from it.

 Clear the JSON from it and paste below JSON and name it LambdaTest

{"input":"Pratap"}


Save it and now you select "LambdaTest" in the drodown beside Test button,  Just click the TEST button.

You can see the output in the details. 

Step 5: Access and Execute Lambda function from AWS CLI

You need to download AWS CLI for windows and install it. Here is the link

Once installed , how do you know if it is installed? Open powershell and run "aws" command.


Unlike Management console, you are not yet authenticated to access your AWS assets from CLI.
to set your credentials use command "aws configure".
It will prompt both AccessID Key and Secret key. This is where you use the keys you saved from earlier in Step1.
After that it will prompt region , if you choose Oregon as i asked you can enter "us-west-2".
and give "json" as defaut output format.

Doing this will create a "credentials" file in "c:\users\<user>\.aws" folder. You can see the Accesskey and Secretkey saved in that file. So next time you dont need to authenticate in CLI. If you want to reauthenticate CLI with other user, just delete or update the file.

Run below command to see if you can access lambda function we created in console. Function name is case-sensitive

aws lambda get-function --function-name MyFirstLambda


There you go, we can access the Lambda function via CLI. Now how to run it and test it.

aws lambda invoke --function-name MyFirstLambda --payload '{\"input\": \"pratap\"}' output.txt


StatusCode:200 shows that execution was sucessfull and if you open the output.txt , you can see the out put.

Step 6: Understand how to pass parameters when calling Lambda function.

--payload '{\"input\": \"pratap\"}' 

From the above code you see that --payload is the parameter to which you need to assign the event json. But its not always small and this easy. So writing everything on one line is not possible.

In that case you can put all the payload json in a file and use that file as payload.

aws lambda invoke --function-name MyFirstLambda --payload 'payload.txt' output.txt

Step7: Error Handling and Logging

When you are dealing with complex Lambda functions, you may run into issues with your code.

Did you see this Amazon CloudWatch Logs trigger in designer , this will e attached to your function by default and logs every function call. But if you havent handled exceptions in the code properly, the log information is not much of a use to debug.

For sake of generating an excption i am chnaging my code and LambdaTest unit test code a bit.
Here is my UnitTest json. I replaced input key with input1.

Now when i execute the test here is the error and the log information on cloudwatch.

I will change the code and try handle the error.

import json
import logging

def lambda_handler(event, context):

    try:
        input=event["input"]
        return {
            'statusCode': 200,
            'body': json.dumps('Hello '+input+', Welcome to AWS Lambda')
        }
    except:
        logging.error("parameter input is not supplied")
        return {
            'statusCode': 500,
            'body': json.dumps("parameter input is not supplied")
        }

Now look at the out put and the log in cloudwatch.


I changed the staus code to 500 thus signifying its an internal server error, and also giving the error message. Using Logging, i am also logging the error message in cloud watch, thus the historical information can be retained in cloudwatch for your Lambda issues.

In our next module we will see how we can leverage AWS LEX using AWS Lambda.

1 comment: