Created
June 13, 2022 14:00
-
-
Save 76creates/47496fe3aa56bc2249943add438c34ac to your computer and use it in GitHub Desktop.
Calculate on-demand EC2 cost of captured instances
This file contains hidden or 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
# This was initially created to calculate the cost of the static infrastructure only | |
# excluding some instance which were dynamic, you can use this to calculate your | |
# instance cost per month and to date cost filtered by regex expression, it does this | |
# for your instances region thus is precise when it comes to cost, tho it uses curent | |
# cost and does not have historical cost data | |
# INSTANCE_RE regex with which we filter instances of interest | |
INSTANCE_RE='^[0-9a-z]{8}-([0-9a-z]{4}-){3}' | |
# INSTANCE_RE_INVERT set to '.' if you want to match regualar, and to 'not' if you want to inverse regex capture | |
INSTANCE_RE_INVERT='not' | |
INSTANCE_REGION='eu-central-1' | |
#TIMEZONE_DIFF is timezone difference from UTC, if our system time is CEST we would add +2 there, leave empty if your system time is UTC | |
TIMEZONE_DIFF='+2' | |
PRICING_MODEL=$(aws --region=us-east-1 pricing get-products --service-code AmazonEC2 --filters Type=TERM_MATCH,Field=regionCode,Value=$INSTANCE_REGION Type=TERM_MATCH,Field=tenancy,Value=Shared Type=TERM_MATCH,Field=operatingSystem,Value=Linux Type=TERM_MATCH,Field=licenseModel,Value="No License required" Type=TERM_MATCH,Field=operation,Value=RunInstances Type=TERM_MATCH,Field=capacitystatus,Value=Used | jq -c '.PriceList[] | fromjson | {"\(.product.attributes.instanceType)" : "\(.terms.OnDemand[].priceDimensions[].pricePerUnit.USD)"}' | jq -s 'map( {(keys[0]): .[]} ) | add') | |
aws --region=$INSTANCE_REGION ec2 describe-instances | jq --argjson pricingModel "$PRICING_MODEL" -r ' | |
.Reservations[].Instances[] | | |
. as $k | | |
$k.Tags[] | | |
select(.Key == "Name") | | |
if (.Value | test("'`echo $INSTANCE_RE`'") | '`echo $INSTANCE_RE_INVERT`' ) | |
then "\($k.LaunchTime) \($k.InstanceId) \($k.InstanceType) \(24 * 30 * ($pricingModel."\($k.InstanceType)" | tonumber)) \($k.LaunchTime | strptime("%Y-%m-%dT%H:%M:%S+00:00") | mktime as $launch | ((((now - $launch) / 60 / 60) '`echo $TIMEZONE_DIFF`') * ($pricingModel."\($k.InstanceType)" | tonumber))) \"\(.Value)\"" | |
else empty | |
end' | sort -t- -k1,1 -k2,2 -k3,3 -k4,4 | awk '{sum+=$4; sumTotal+=$5; print "["$1"] "$2" "$3" 30days:"$4" fromStart:"$5" name:"$6} END {print "30days:"sum" fromStart:"sumTotal}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment