aboutsummaryrefslogtreecommitdiff
path: root/sections/costexplorer.py
diff options
context:
space:
mode:
authorChristian Cleberg <hello@cleberg.net>2025-06-20 13:55:54 -0500
committerChristian Cleberg <hello@cleberg.net>2025-06-20 13:55:54 -0500
commit785f42901f34aaf356f316c691e3f56138c8608d (patch)
tree5b8f7a6e33a6af410e511137fdd51b6fa60d0f83 /sections/costexplorer.py
downloadaws-summary-report-785f42901f34aaf356f316c691e3f56138c8608d.tar.gz
aws-summary-report-785f42901f34aaf356f316c691e3f56138c8608d.tar.bz2
aws-summary-report-785f42901f34aaf356f316c691e3f56138c8608d.zip
initial commit
Diffstat (limited to 'sections/costexplorer.py')
-rw-r--r--sections/costexplorer.py67
1 files changed, 67 insertions, 0 deletions
diff --git a/sections/costexplorer.py b/sections/costexplorer.py
new file mode 100644
index 0000000..66747f0
--- /dev/null
+++ b/sections/costexplorer.py
@@ -0,0 +1,67 @@
+# costexplorer.py
+import boto3
+import datetime
+from tabulate import tabulate
+
+
+def get_section(config):
+ profile = config["aws"].get("profile")
+ region = config["aws"]["region"]
+
+ session = boto3.Session(
+ profile_name=profile if profile else None, region_name=region
+ )
+ client = session.client("ce")
+
+ today = datetime.date.today()
+ start = (today - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
+ end = today.strftime("%Y-%m-%d")
+
+ response = client.get_cost_and_usage(
+ TimePeriod={"Start": start, "End": end},
+ Granularity="DAILY",
+ Metrics=["UnblendedCost"],
+ GroupBy=[{"Type": "DIMENSION", "Key": "SERVICE"}],
+ )
+
+ results = response["ResultsByTime"][0]
+ date = results["TimePeriod"]["Start"]
+ estimated = results.get("Estimated", False)
+
+ rows = []
+ groups = results.get("Groups", [])
+ if groups:
+ for group in groups:
+ service = group["Keys"][0]
+ cost = (
+ group.get("Metrics", {}).get("UnblendedCost", {}).get("Amount", "0.00")
+ )
+ rows.append([service, f"${float(cost):.2f}"])
+ else:
+ rows.append(["No service-level data available", ""])
+
+ total_cost = results.get("Total", {}).get("UnblendedCost", {}).get("Amount", None)
+ if total_cost is None:
+ total_cost = sum(
+ float(group.get("Metrics", {}).get("UnblendedCost", {}).get("Amount", 0.0))
+ for group in groups
+ )
+ rows.append(["TOTAL", f"${float(total_cost):.2f}"])
+
+ table = tabulate(
+ rows,
+ headers=["Service", "Cost"],
+ tablefmt="simple_grid",
+ colalign=("left", "right"),
+ )
+
+ lines = [
+ f"AWS Billing Report for {date}",
+ f"[https://{config['aws'].get('region')}.console.aws.amazon.com/costmanagement/]",
+ table,
+ ]
+
+ if estimated:
+ lines.append("\nNote: Costs are estimated and may change.")
+
+ return "\n".join(lines)