How to Determine the Cost of an AWS Resource for the Previous Month

What will you learn?

In this comprehensive tutorial, you will master the art of tracking and calculating costs associated with a specific Amazon Web Services (AWS) resource for the previous month. By leveraging AWS Cost Explorer API and Python scripting, you will gain valuable insights into your cloud expenses, enabling efficient budget management and cost optimization.

Introduction to the Problem and Solution

Managing applications or services in AWS demands meticulous cost monitoring. With diverse pricing models across AWS services, deciphering your bill can be daunting. To address this challenge effectively, we will harness the power of AWS Cost Explorer API. Through automated requests using Python scripts, we can extract precise cost data for any tagged resource within our account. This approach not only simplifies cost tracking but also facilitates streamlined budget automation processes.

Code

import boto3
from datetime import datetime, timedelta

# Initialize Cost Explorer client
client = boto3.client('ce')

def get_last_month_cost(resource_tag_key, resource_tag_value):
    # Calculate start and end dates for last month
    today = datetime.now()
    first_day_last_month = (today.replace(day=1) - timedelta(days=1)).replace(day=1)
    last_day_last_month = today.replace(day=1) - timedelta(days=1)

    try:
        response = client.get_cost_and_usage(
            TimePeriod={
                'Start': first_day_last_month.strftime('%Y-%m-%d'),
                'End': last_day_last_month.strftime('%Y-%m-%d')
            },
            Granularity='MONTHLY',
            Filter={
                'Tags': {
                    'Key': resource_tag_key,
                    'Values': [resource_tag_value]
                }
            },
            Metrics=["UnblendedCost"]
        )
        return response['ResultsByTime'][0]['Total']['UnblendedCost']['Amount']
    except Exception as e:
        print(f"Error fetching cost data: {e}")

# Example usage
cost = get_last_month_cost('Project', 'YourProjectName')
print(f"Last month's cost: ${cost}")

# Copyright PHD

Explanation

The code snippet showcases querying AWS Cost Explorer using Boto3 to retrieve the unblended cost of resources tagged with specific key-value pairs for the previous month. – Boto3 Client Initialization: Creation of a boto3 client for ce (Cost Explorer). – Calculating Date Range: Determination of start and end dates for the previous month. – API Request: Utilization of get_cost_and_usage to request cost data based on specified parameters like time period and tags.

Upon successful execution, it displays the total unblended cost from last month associated with the provided tags.

    How do I set up Boto3?

    To set up Boto3, ensure you have an AWS account configured on your machine via environment variables or .aws/credentials. Then install Boto3 using pip: pip install boto3.

    What are Unblended Costs?

    Unblended Costs represent raw rates of each usage type multiplied by its usage amount without factoring in consolidated billing discounts or adjustments.

    Can I track multiple tags simultaneously?

    Yes! Adjust the filter section within get_cost_and_usage() call accordingly�AWS supports AND/OR logic within filters.

    Is granularity finer than monthly supported?

    Absolutely! While our example uses monthly granularity (‘MONTHLY’), finer options like ‘DAILY’ or even ‘HOURLY’ are available based on requirements.

    What if my resources lack tags?

    Tagging resources is crucial; untagged resources won’t yield results when filtered by tag. Start tagging your resources promptly!

    Are there limitations on API requests?

    Be mindful of AWS’s rate limits on Cost Explorer API requests to avoid exceeding them in automated scripts.

    Conclusion

    Monitoring cloud expenditure closely empowers informed decision-making regarding scaling operations based on actual data-driven insights from past periods. Leveraging tools like Boto3 alongside native capabilities offered by platforms such as AWS streamlines this complex task�enabling teams to achieve operational excellence through financial prudence.

    Leave a Comment