AWS Lambda function to check whether a website is up and running using Python

Website downtime can be detrimental to your business. To ensure your website is always up and running, you can create an AWS Lambda function that periodically checks the website’s availability. In this article, we will show you how to set up an AWS Lambda function to monitor a website’s uptime.

Before you begin, make sure you have the following prerequisites in place:

  1. An AWS account.
  2. AWS Lambda function created.
  3. Basic knowledge of Python programming.

Step 1: Create an AWS Lambda Function

  1. Log in to your AWS Management Console and navigate to the Lambda service.
  2. Click on the “Create Function” button to create a new Lambda function.
  3. Choose a name for your Lambda function and select the runtime as “Python.”
  4. In the “Function code” section, you can either write your Python code directly in the Lambda console or upload a .zip file containing your code. In this example, we’ll write the code directly in the console.

Step 2: Write the Lambda Function Code

import requests
#Training for learn @ https://www.freshers.in
def lambda_handler(event, context):
    url = "https://www.yourwebsite.com"  # Replace with the URL of the website you want to monitor
    
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return "Website is UP"
        else:
            return "Website is DOWN"
    except Exception as e:
        return f"An error occurred: {str(e)}"

Make sure to replace "https://<code class="language-python">yourwebsite.com” with the URL of the website you want to monitor.

Step 3: Set Up a CloudWatch Event Trigger

To schedule the Lambda function to run periodically, you can use Amazon CloudWatch Events as a trigger. Follow these steps:

  1. In the Lambda function configuration, go to the “Add trigger” section.
  2. Select “CloudWatch Events” as the trigger type.
  3. Configure the event source with the desired schedule (e.g., cron expression) for how often you want the Lambda function to check the website’s uptime.
  4. Click “Add” to add the trigger.

Step 4: Test the Lambda Function

You can manually test the Lambda function by clicking the “Test” button in the Lambda console. This will simulate the Lambda function execution and display the result.

Step 5: Monitor Website Uptime

Now, your Lambda function is set up to periodically check the website’s uptime based on the schedule you defined in CloudWatch Events. You can monitor the website’s status by reviewing the CloudWatch Logs for your Lambda function.

Author: user