Skip to content

Instantly share code, notes, and snippets.

@marcusramberg
Created December 8, 2022 20:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcusramberg/9ce531a110baba303f145e89361a5a19 to your computer and use it in GitHub Desktop.
Save marcusramberg/9ce531a110baba303f145e89361a5a19 to your computer and use it in GitHub Desktop.
#!/usr/bin/python3
import os
import json
import subprocess
infracost_output = os.environ.get("INFRACOST_OUTPUT")
if infracost_output is None:
print("Expected INFRACOST_OUTPUT ENV variable not found")
exit(1)
infracost_file = open(infracost_output)
infracost = json.load(infracost_file)
past_total_monthly_cost = float(infracost['pastTotalMonthlyCost']) or 0
total_monthly_cost = float(infracost['totalMonthlyCost']) or 0
diff_total_monthly_cost = float(infracost["diffTotalMonthlyCost"]) or 0
currency = infracost['currency']
if currency == "" or currency == "USD":
currency = "$"
elif currency == "EUR":
currency = "€"
elif currency == "GBP":
currency = "£"
# Run infracost output to get the diff output
res = subprocess.run(["infracost", "output", "--no-color", "--format", "diff", "--show-skipped",
f"--path={infracost_output}"],
capture_output=True, encoding="utf-8")
diff_output = res.stdout
def change_symbol(old, new):
change_symbol = "+"
if new < old:
change_symbol = "-"
return change_symbol
def percent_display(old, new):
percent = calculate_percentage(old, new)
sym = change_symbol(old, new)
return f"{sym}{percent}%"
def calculate_percentage(old, new):
# If both old and new costs are greater than 0
if old > 0 and new > 0:
percent = (new / old * 100) - 100
# If both old and new costs are less than or equal to 0
if old <= 0 and new <= 0:
percent = 0
if old <= 0 and new > 0:
percent = 100
return percent
def format_cost(cost):
if cost is None or cost == "":
return "-"
elif cost < 100:
return "{}{:0.2f}".format(currency, cost)
else:
return "{}{:0.0f}".format(currency, cost)
percent = percent_display(past_total_monthly_cost, total_monthly_cost)
# FIXME: double percent?
change_word = "increase"
if past_total_monthly_cost > total_monthly_cost:
change_word = "decrease"
print(f"""
############################### 💰 Infracost estimate 💰 ###############################"
Monthly cost will {change_word} by {format_cost(diff_total_monthly_cost)} {percent}
Previous monthly cost: {format_cost(past_total_monthly_cost)}
New monthly cost: {format_cost(total_monthly_cost)}
Infracost output:
""")
print(diff_output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment