Created
July 5, 2024 09:44
-
-
Save arshpreetsingh/fb1f69252da1880e086e29fac6476677 to your computer and use it in GitHub Desktop.
cost-details
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
from datetime import datetime, timedelta | |
from pprint import pprint | |
# Replace with your AWS access key, secret key, and region | |
client = boto3.client('ce', | |
aws_access_key_id='YOUR_ACCESS_KEY', | |
aws_secret_access_key='YOUR_SECRET_KEY', | |
region_name='YOUR_REGION') | |
# Get the cost for the last month (or adjust time range as needed) | |
end_date = datetime.now() | |
start_date = end_date - timedelta(days=30) | |
# Filter for Aurora PostgreSQL costs (adjust filters for your resources) | |
filters = [ | |
{'Dimensions': {'Key': 'SERVICE', 'Values': ['AmazonRDS']}}, | |
{'Dimensions': {'Key': 'DATABASE_ENGINE', 'Values': ['Aurora PostgreSQL']}}, | |
# You can add more filters for specific instances using tags, etc. | |
] | |
# Fetch the cost and usage data | |
response = client.get_cost_and_usage( | |
TimePeriod={ | |
'Start': start_date.strftime('%Y-%m-%d'), | |
'End': end_date.strftime('%Y-%m-%d') | |
}, | |
Granularity='DAILY', # Change to MONTHLY for monthly costs | |
Metrics=['BlendedCost'], | |
GroupBy=[ | |
{'Type': 'DIMENSION', 'Key': 'USAGE_TYPE'}, | |
{'Type': 'DIMENSION', 'Key': 'DATABASE_ENGINE'} | |
], | |
Filter={"And": filters} | |
) | |
# Process and display the results | |
cost_data = {} | |
for group in response['ResultsByTime'][0]['Groups']: | |
keys = [d['Key'] for d in group['Keys']] | |
usage_type, database_engine = keys | |
cost = float(group['Metrics']['BlendedCost']['Amount']) | |
if usage_type not in cost_data: | |
cost_data[usage_type] = {} | |
cost_data[usage_type][database_engine] = cost | |
pprint(cost_data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment