Skip to content

Instantly share code, notes, and snippets.

@dgulinobw
Created December 8, 2020 23:10
Show Gist options
  • Save dgulinobw/33bee72ce1e58d68c78f8f8c6d64434f to your computer and use it in GitHub Desktop.
Save dgulinobw/33bee72ce1e58d68c78f8f8c6d64434f to your computer and use it in GitHub Desktop.
Split EC2 savings plan savings between product tags
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import csv
from functools import reduce
from operator import add
import boto3
ce = boto3.client('ce')
start_date="2020-11-01"
end_date="2020-12-01"
costs=ce.get_cost_and_usage(TimePeriod={"Start":start_date,"End":end_date},GroupBy=[{"Type":"TAG", "Key":"product"}],Granularity="MONTHLY",Metrics=["UnblendedCost"])
groups=costs["ResultsByTime"][0]["Groups"]
costs={group.get('Keys')[0].split("$")[1]: {"total": float(group.get("Metrics")["UnblendedCost"]["Amount"])} for group in groups}
costs["savings_plan"] = costs.pop("")
products = costs.keys()
for product in products:
try:
coverage=ce.get_savings_plans_coverage(
TimePeriod={"Start":start_date,"End":end_date},
Filter={"CostCategories":{"Key":product,"Values":["product tag"]}})
spend_coverage=coverage["SavingsPlansCoverages"][0]["Coverage"]["SpendCoveredBySavingsPlans"]
costs[product]["spend_coverage"] = float(spend_coverage)
except ce.exceptions.DataUnavailableException:
costs[product]["spend_coverage"] = 0.0
all_spend=[float(costs.get(product)["spend_coverage"]) for product in costs.keys()]
total_spend = reduce(add, all_spend)
total_savings_plan=costs["savings_plan"]["total"] * -1.0
for product in costs:
costs[product]["percent_spend"] = (costs[product]["spend_coverage"] / total_spend * 100)
costs[product]["savings"] = (total_savings_plan / 100 ) * costs[product]["percent_spend"]
costs[product]["total_with_savings"] = costs[product]["total"] - costs[product]["savings"]
costs = dict(sorted(costs.items(), key=lambda item: item[0]))
data_file = open('aws_costs_with_savings_plans_' + start_date + '-' + end_date + '.csv', 'w')
csv_writer = csv.writer(data_file)
header = list(costs['savings_plan'].keys())
header.insert(0,'product')
csv_writer.writerow(header)
for product in costs.keys():
row = list(costs[product].values())
row.insert(0,product)
csv_writer.writerow(row)
data_file.close()
#print(json.dumps(costs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment