DEV Community

Randika Madhushan Perera
Randika Madhushan Perera

Posted on

AWS Lambda Guide (Lesson 02)

AWS Lambda Guide Lesson 01: Lesson 01

series

2. Lambda Fundamentals

2.4 Creating a Lambda Function

In this section, we are going to create a lambda function in the AWS console test it, and generate a log that we'll view in CloudWatch.

This lambda function will check whether a website is up or not and generate logs in CloudWatch.

Lambda-fun

Step 01:

Go to your AWS console and navigate for the Lambda.

step01

Step 02:

Click "Create Function" and create a function with the below details.

step02

Click on the "Change default execution role" and expand it. After that select "Create a new role with basic Lambda permissions".

step02-1

Create the function.

Step 03:

Create a basic hello-world test event to test the Lambda function. This test will invoke the function and determine the HTTP response code for the website in the code. Feel free to modify the Lambda code to test other websites and review the response codes within the function.

add the below code in the "index.js" file.

import https from 'https';

let url = "https://www.amazon.com";

export async function handler(event) {
    let statusCode;
    await new Promise((resolve, reject) => {
        https.get(url, (res) => {
            statusCode = res.statusCode;
            resolve(statusCode);
        }).on('error', (e) => {
            reject(Error(e));
        });
    });
    console.log(statusCode);
    return statusCode;
}
Enter fullscreen mode Exit fullscreen mode

Now click the "Deploy" button.

Step 04:

We will create a test event and execute the Lambda.

step04

Give a name for the test event and save it.

step04-1

Step 05:

Now test the function. After clicking the test button you will able to see "Response 200"

step05

Step 06:

After you've tested the function, navigate to CloudWatch to review the logs for the test event.

Top comments (0)