DEV Community

Cover image for Automated AWS Bill Reminder System using Serverless Architecture with AWS Lambda
Rahul Kumar Sharma
Rahul Kumar Sharma

Posted on

Automated AWS Bill Reminder System using Serverless Architecture with AWS Lambda

The aim is to develop a serverless system using AWS Lambda to notify users when their AWS bill is pending, to ensure timely payment and avoid disruptions to AWS services.

Components:

  • AWS Lambda Functions: Use Lambda functions to periodically check the status of AWS billing and send notifications to users when their bills are pending.
  • AWS Billing and Cost Management: Utilize AWS Billing and Cost Management services to retrieve billing information and check the status of pending bills.
  • Amazon SNS: Use Amazon Simple Notification Service (SNS) to send email notifications to users when their AWS bills are pending.
  • AWS CloudWatch Events: Set up CloudWatch Events to trigger Lambda functions at regular intervals for checking the billing status.
  • AWS SDKs: Leverage AWS SDKs (e.g., Boto3 for Python) to interact with AWS services programmatically and automate billing notifications.

Steps to Implement:

Set up IAM Roles:

  • To send notifications via Amazon SNS and use AWS Billing and Cost Management services, create an IAM role with the necessary permissions.

Write Lambda Function:

  • Develop a Lambda function that retrieves billing information using the AWS SDK.
  • Implement logic to check if the bill is pending and trigger a notification if necessary.

Configure CloudWatch Event Rule:

  • Set up a CloudWatch Event rule to trigger the Lambda function at regular intervals (e.g., daily, weekly) to check the billing status.

Implement Notification Logic:

  • Use the SNS service to send email notifications to users when their AWS bills are pending.
  • Customize the notification message with relevant billing details and instructions for payment.

Handle Error Cases:

  • Incorporate error handling into the Lambda function to handle exceptions, including failed service requests and incorrectly retrieved billing data.
  • Configure appropriate logging and monitoring using CloudWatch to track function executions and errors.

Testing:

  • Test the Lambda function and CloudWatch Event rule to ensure they trigger notifications correctly based on the billing status.
  • Verify that users receive notifications as expected and that the notification content is accurate.

Deployment:

  • Deploy the Lambda function and CloudWatch Event rule in the AWS account where billing notifications are required.
  • Configure necessary permissions and IAM roles for the Lambda function to access AWS Billing and SNS services.

Monitor and Maintain:

  • Monitor the execution of Lambda functions and CloudWatch Events to ensure they run as scheduled and handle any failures or exceptions promptly.
  • Periodically review and update the system to accommodate changes in AWS billing policies or user requirements.

Lambda Function:

import json
import boto3

def lambda_handler(event, context):
    # Initialize AWS services
    sns_client = boto3.client('sns')
    billing_client = boto3.client('ce')  # AWS Cost Explorer

    # Retrieve billing information
    response = billing_client.get_cost_and_usage(
        TimePeriod={
            'Start': '2024-01-01',
            'End': '2024-03-01'  # Modify the date range as needed
        },
        Granularity='MONTHLY',
        Metrics=['UnblendedCost']  # You can customize the metrics as needed
    )

    # Extract the total cost for the current billing period
    total_cost = float(response['ResultsByTime'][0]['Total']['UnblendedCost']['Amount'])

    # Check if the bill is pending (total cost > 0)
    if total_cost > 0:
        # Send notification
        topic_arn = 'arn:aws:sns:ap-south-1:965519929135:awsBillNotification'  # Replace with your SNS topic ARN
        message = f'Your AWS bill for the current month is pending. Total amount due: ${total_cost:.2f}'
        subject = 'Action Required: Your AWS Bill is Pending'

        sns_client.publish(
            TopicArn=topic_arn,
            Message=message,
            Subject=subject
        )

        print('Billing notification sent successfully')
    else:
        print('No pending bills found')

    return {
        'statusCode': 200,
        'body': 'Billing notification process completed'
    }


Enter fullscreen mode Exit fullscreen mode

Testing:

Lambda Test

Output:

Email Output

Find me Online!

Top comments (0)