krz/aws-summary-report

Automated AWS summary reports, straight to your inbox.

clone: git clone https://gitbay.org/krz/aws-summary-report.git

main: sections/costexplorer.py · raw

 1# costexplorer.py
 2import boto3
 3import datetime
 4from tabulate import tabulate
 5
 6
 7def get_section(config):
 8    profile = config["aws"].get("profile")
 9    region = config["aws"]["region"]
10
11    session = boto3.Session(
12        profile_name=profile if profile else None, region_name=region
13    )
14    client = session.client("ce")
15
16    today = datetime.date.today()
17    start = (today - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
18    end = today.strftime("%Y-%m-%d")
19
20    response = client.get_cost_and_usage(
21        TimePeriod={"Start": start, "End": end},
22        Granularity="DAILY",
23        Metrics=["UnblendedCost"],
24        GroupBy=[{"Type": "DIMENSION", "Key": "SERVICE"}],
25    )
26
27    results = response["ResultsByTime"][0]
28    date = results["TimePeriod"]["Start"]
29    estimated = results.get("Estimated", False)
30
31    rows = []
32    groups = results.get("Groups", [])
33    if groups:
34        for group in groups:
35            service = group["Keys"][0]
36            cost = (
37                group.get("Metrics", {}).get("UnblendedCost", {}).get("Amount", "0.00")
38            )
39            rows.append([service, f"${float(cost):.2f}"])
40    else:
41        rows.append(["No service-level data available", ""])
42
43    total_cost = results.get("Total", {}).get("UnblendedCost", {}).get("Amount", None)
44    if total_cost is None:
45        total_cost = sum(
46            float(group.get("Metrics", {}).get("UnblendedCost", {}).get("Amount", 0.0))
47            for group in groups
48        )
49    rows.append(["TOTAL", f"${float(total_cost):.2f}"])
50
51    table = tabulate(
52        rows,
53        headers=["Service", "Cost"],
54        tablefmt="simple_grid",
55        colalign=("left", "right"),
56    )
57
58    lines = [
59        f"AWS Billing Report for {date}",
60        f"[https://{config['aws'].get('region')}.console.aws.amazon.com/costmanagement/]",
61        table,
62    ]
63
64    if estimated:
65        lines.append("\nNote: Costs are estimated and may change.")
66
67    return "\n".join(lines)