• DevOps
    Case Study

    How we built a resilient multi-account, multi-cloud solution for a Health Tech service provider!

    READ CASESTUDY
    icon

    24/7 DevOps as a Service

    Round-the-clock DevOps for uninterrupted efficiency.

    icon

    Infrastructure as a Code

    Crafting infrastructure with ingenious code.

    icon

    CI/CD Pipeline

    Automated CI/CD pipeline for seamless deployments.

    icon

    DevSecOps

    Integrated security in continuous DevOps practices.

    icon

    Hire DevOps Engineers

    Level up your team with DevOps visionaries.

    icon

    Consulting Services

    Navigate success with expert DevOps consulting.

  • TechOps
    Case Study

    How we built a scalable Odoo solution for a Travel Tech service provider!

    READ CASESTUDY

    WEB HOSTING SUPPORT

    icon

    HelpDesk Support

    Highly skilled 24/7 HelpDesk Support

    icon

    Product Support

    Boost your product support with our expertise.

    MANAGED SERVICES

    icon

    Server Management

    Don’t let server issues slow you down. Let us manage them for you.

    icon

    Server Monitoring

    Safeguard your server health with our comprehensive monitoring solutions.

    STAFF AUGMENTATION

    icon

    Hire an Admin

    Transform your business operations with our expert administrative support.

    icon

    Hire a Team

    Augment your workforce with highly skilled professionals from our diverse talent pool.

  • CloudOps
    Case Study

    How we helped a Private Deemed University in India, save US $3500/m on hosting charges!

    READ CASESTUDY
    icon

    AWS Well Architected Review

    Round-the-clock for uninterrupted efficiency

    icon

    Optimize

    Efficient CloudOps mastery for seamless cloud management

    icon

    Manage

    Automated CI/CD pipeline for seamless deployments

    icon

    Migrate

    Upgrade the journey, Migrate & Modernize seamlessly

    icon

    Modernize

    Simplify compliance complexities with our dedicated services

    icon

    FinOps as a Service

    FinOps as a Service

  • SecOps
    Case Study

    How we built a scalable Odoo solution for TravelTech service provider!

    READ CASESTUDY
    icon

    VAPT

    Vulnerability Assessment and Penetration Testing

    icon

    Source Code Review

    Ensuring source code security ans safe practices to reduce risks

    icon

    Security Consultation

    On demand services for improving server security

    icon

    System Hardening

    Reduced vulnerability and proactive protection

    icon

    Managed SoC

    Monitors and maintains system security. Quick response on incidents.

    icon

    Compliance as a Service

    Regulatory compliance, reduced risk

  • Insights
    Case Study

    How we helped a Private Deemed University in India, save US $3,500/m on hosting charges!

    READ CASESTUDY
    icon

    Blog

    Explore our latest articles and insights

    icon

    Case Studies

    Read about our client success stories

    icon

    Flipbook

    Explore our latest Flipbook

    icon

    Events

    Join us at upcoming events and conferences

    icon

    Webinars

    Watch our educational webinar series

  • Our Story
  • Contact Us

Interested to collaborate?

Get in touch with us!

Ready to elevate your business with certified cloud expertise? Contact us today to learn how our team can help you leverage cloud technology to drive growth, streamline operations, and enhance security.

  • AWSAWS
  • Azure CloudAzure Cloud
  • Google CloudGoogle Cloud
  • Akamai CloudAkamai Cloud
  • OVHOVH
  • Digital OceanDigital Ocean
  • HetznerHetzner
  • Kubernetes Consultancy Services
  • K8s & Cloud native Solutions
  • 24/7 Infrastructure Monitoring
  • DevOps as a Service
  • Cloud CI/CD Solutions
  • White Labeled MSP Support
  • Our story
  • Life@SupportSages
  • Insights
  • Careers
  • Events
  • Contact Us

Connect with us!


LinkedInFacebookXInstagramYouTube

aws partneraws advanced partner
SupportSages

Copyright © 2008 – 2026 SupportSages Pvt Ltd. All Rights Reserved.
Privacy PolicyLegal TermsData ProtectionCookie Policy
Generate Cost and Usage Reports in AWS Lambda Using Python and Boto3

Generate Cost and Usage Reports in AWS Lambda Using Python and Boto3

Arya P B

  • 4 min read
Generate Cost and Usage Reports in AWS Lambda Using Python and Boto3

Generating audio, please wait...

AWS Cost Explorer provides valuable insights into your AWS usage and spending. In this tutorial, we will walk through a Lambda function that generates a CSV report of AWS cost and usage data for a specified date range, focusing on services consumed by a specific AWS account.

Prerequisites

  1. AWS Lambda: Ensure you have permissions to access AWS Cost Explorer.
  2. AWS Cost Explorer API Access: Set up the necessary permissions for the ce:GetCostAndUsage action in your Lambda execution role.

The Lambda Function Code

Below is the complete Python script that we will deploy as an AWS Lambda function.

import json
import boto3
import csv
import io

client = boto3.client('ce')

def lambda_handler(event, context):
    try:
        print("Event:", event)
        
        input_data = json.loads(event['input'])
        start_date = input_data.get('startDate')
        end_date = input_data.get('endDate')
        
        print(f"Start Date: {start_date}, End Date: {end_date}")

        response = client.get_cost_and_usage(
            TimePeriod={
                'Start': start_date,
                'End': end_date
            },
            Granularity='DAILY',
            Metrics=[
                'AmortizedCost',
            ],
            GroupBy=[
                {
                    'Type': 'DIMENSION',
                    'Key': 'SERVICE'
                },
            ],
            Filter={
                'Dimensions': {
                    'Key': 'LINKED_ACCOUNT',
                    'Values': ['Account-Id'] //provide account id
                }
            }
        )
        
        csv_output = io.StringIO()
        csv_writer = csv.writer(csv_output)

        header = ['Date', 'Service', 'AmortizedCost']
        csv_writer.writerow(header)

        results = response['ResultsByTime']
        for result in results:
            date = result['TimePeriod']['Start']
            csv_writer.writerow([f"Date: {date}", "", ""])
            
            for group in result['Groups']:
                service = group['Keys'][0]
                cost = group['Metrics']['AmortizedCost']['Amount']
                csv_writer.writerow([date, service, cost])

            csv_writer.writerow(["", "", ""]) 
        csv_data = csv_output.getvalue()
        print(csv_data)

        return {
            'statusCode': 200,
            'body': csv_data,
            'headers': {
                'Content-Type': 'text/csv',
                'Content-Disposition': 'attachment; filename="cost_usage_report.csv"'
            }
        }

    except Exception as e:
        return {
            'statusCode': 500,
            'body': json.dumps({"error": str(e)}),
            'headers': {
                'Content-Type': 'application/json'
            };
        }

Code Explanation

  1. Initialization:
  • We import required modules: json, boto3 (AWS SDK for Python), csv, and io.
  • The boto3.client('ce') line initializes the AWS Cost Explorer client.
  1. Handling Events:
  • The lambda_handler function receives an event containing the startDate and endDate parameters, which specify the date range for the report.
  • We parse these parameters using json.loads(event['input']) and extract the required date values.
  1. Fetching Cost and Usage Data:
  • The get_cost_and_usage method is called to retrieve the cost data, grouped by service, within the specified date range.
  • The Filter parameter is set to limit the data to a specific AWS account ID
  1. Generating the CSV Report:
  • We create a CSV output using io.StringIO() and write headers with csv_writer.writerow(header).
  • For each result in the response, we write the date, service, and amortized cost values to the CSV.
  1. Returning the Response:
  • The CSV data is returned in the response body with appropriate content headers to make it downloadable.

Deploying the Lambda Function

To deploy this function:

  1. Go to the AWS Lambda Console.
  2. Create a new function and paste the above code into the code editor.
  3. Set up the necessary IAM role with permissions for Cost Explorer.
  4. Test the function with a sample event that includes startDate and endDate.

Sample Input Event

Here’s a sample input to test your Lambda function:

{
  "input": "{\"startDate\": \"2023-09-01\", \"endDate\": \"2023-09-30\"}"
}

Conclusion

This Lambda function allows you to automate the process of generating daily AWS cost reports by service, helping you gain insights into your AWS spending. By customizing the event parameters, you can easily generate reports for any date range and download them as CSV files.

Take control of your AWS spending! Implement this Lambda function to automate your cost reporting and gain valuable insights into your AWS usage. Don’t wait, start optimizing your cloud costs today by generating detailed CSV reports that keep your budget on track! - 

  • DevOps
Promotional banner
Promotional banner

Analyzing AWS IAM Users: Access Key and Password Age

Analyzing AWS IAM Users: Access Key and Password Age
  • DevOps
logo

Analyzing AWS IAM Users: Access Key and Password Age

Analyzing AWS IAM Users: Access Key and Password Age
  • AWS
  • DevOps
logo

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide
  • DevOps
logo

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide

Auto-Restart EC2 Instances on Status Check Failure: Quick Setup Guide
  • AWS
  • DevOps
logo

Posts by Arya P B

Athena