DEV Community

Cover image for Automated Reporting System
ADEEL ABBAS
ADEEL ABBAS

Posted on

Automated Reporting System

Overview
We’ll build a system using AWS Lambda and other serverless tools to automate daily reporting. The system will:

  1. Collect data from multiple sources.
  2. Generate a PDF report.
  3. Send the report via email.
  4. Trigger this process daily.

This guide assumes you have a basic understanding of AWS. Let’s start!

Step 1: Create an S3 Bucket

  1. Go to the S3 service.
  2. Click Create bucket.
  3. Name your bucket (e.g., daily-reports-s3-bucket).
  4. Keep other settings default and click Create.
  5. This bucket will store the reports if needed.

S3

Step 2: Verify an Email Address in SES

  1. Go to Amazon SES.
  2. Navigate to Email Addresses under Identity Management.
  3. Click Verify a New Email Address and enter your email.
  4. Check your email inbox and click the verification link.

This allows SES to send emails from this address.

SES

Step 3: Write the Lambda Function

  1. Go to AWS Lambda and click the Create function.
  2. Choose:
  • Author from scratch.
  • Function name: daily-report-lambda.
  • Runtime: Python 3.9 (or later).
  • Click the Create function.

Code for the Lambda Function

  • Scroll to the Code section.
  • Replace the default code with the following:
import boto3
from fpdf import FPDF
import os
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders

def lambda_handler(event, context):
    try:
        # Generate the PDF report
        pdf = FPDF()
        pdf.add_page()
        pdf.set_font("Arial", size=12)
        pdf.cell(200, 10, txt="Daily Report", ln=True, align="C")
        pdf.cell(200, 10, txt="This is your automated report.", ln=True)

        # Save the PDF
        report_path = "/tmp/daily_report.pdf"
        pdf.output(report_path)

        # Upload to S3 (Optional)
        s3 = boto3.client('s3')
        bucket_name = "daily-reports-s3-bucket"
        s3.upload_file(report_path, bucket_name, "daily_report.pdf")

        # Send email via SES with attachment using raw email
        ses = boto3.client('ses')
        msg = MIMEMultipart()
        msg['From'] = "sender_email@gmail.com"  # Replace with your SES verified email
        msg['To'] = "receiver_email@gmail.com"  # Replace with recipient email
        msg['Subject'] = "Daily Report"

        # Attach the text body
        body = MIMEText("Please find the attached report.", 'plain')
        msg.attach(body)

        # Attach the PDF report
        with open(report_path, 'rb') as file:
            part = MIMEBase('application', 'octet-stream')
            part.set_payload(file.read())
            encoders.encode_base64(part)
            part.add_header('Content-Disposition', f'attachment; filename={os.path.basename(report_path)}')
            msg.attach(part)

        # Send the email using SES's send_raw_email
        response = ses.send_raw_email(
            Source=msg['From'],
            Destinations=[msg['To']],
            RawMessage={'Data': msg.as_string()}
        )

        return {"status": "success", "response": response}

    except Exception as e:
        return {"status": "error", "message": str(e)}

Enter fullscreen mode Exit fullscreen mode

Step 4: Install Libraries Locally and Deploy (Optional)

You will use third-party libraries like fpdf, as fpdf is not available in Lambda, package them locally:
Install fpdf locally:

  • pip install fpdf

  • Zip the files and upload them to the Lambda function.

lambda

Step 5: Set Up EventBridge Trigger

  • Go to EventBridge.
  • Click Create rule.
  • Name: daily-report-trigger.
  • Define pattern: Schedule.
  • Cron expression: "cron(0 9 * * ? *)" (9:00 AM UTC daily).
  • Under Target, choose your Lambda function (daily-report-lambda).
  • Click Create.

Cron

Step 6: Test the Lambda Function

  • Go to the Test tab in your Lambda function.
  • Create a new test event (leave it blank).
  • Click Test.
  • Check your email inbox for the report.

Report

Complete!

You’ve built a serverless reporting system! 🎉

Happy Cloud Learning

Adeel Abbas

Top comments (0)