Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AWS: check if all reserved instances are in use by appropriate on-demand ones
#!/bin/bash
set -e
REGION="us-west-2"
RUNNING_INSTANCES=`aws ec2 describe-instances --region $REGION --filters Name=instance-state-name,Values=running --query Reservations[*].Instances[*].InstanceType --output text | sort | uniq -c | awk ' { t = $1; $1 = $2; $2 = t; print; } '`
# Example:
#m3.medium 11
#r3.large 3
#t2.medium 14
#t2.micro 45
RESERVED_INSTANCES=`aws ec2 describe-reserved-instances --region $REGION --filter Name=state,Values=active --query ReservedInstances[*].[InstanceType,InstanceCount] --output text | awk '{arr[$1]+=$2} END {for (i in arr) {print i,arr[i]}}' | sort `
# Example:
#m3.medium 10
#r3.large 3
#t2.medium 19
#t2.micro 25
ERROR="false"
IFS=$'\n'
for running_instance in `echo -e "$RUNNING_INSTANCES"` ; do
RUNNING_INSTANCE_TYPE=`echo $running_instance | awk '{print $1}'`
RUNNING_INSTANCE_COUNT=`echo $running_instance | awk '{print $2}'`
RESERVED_INSTANCE_COUNT=`echo "$RESERVED_INSTANCES" | grep $RUNNING_INSTANCE_TYPE | awk '{print $2}'`
if [ -z "$RESERVED_INSTANCE_COUNT" ]; then
RESERVED_INSTANCE_COUNT="0"
fi
DIFF=$(( $RESERVED_INSTANCE_COUNT - $RUNNING_INSTANCE_COUNT ))
if [ "$DIFF" -lt 0 ]; then
echo "[INFO] We can buy $(( $RUNNING_INSTANCE_COUNT - $RESERVED_INSTANCE_COUNT )) more reserved instance(s) of $RUNNING_INSTANCE_TYPE type (current running $RUNNING_INSTANCE_TYPE's count is $RUNNING_INSTANCE_COUNT while current reserved $RUNNING_INSTANCE_TYPE's count is $RESERVED_INSTANCE_COUNT)"
fi
if [ "$DIFF" -gt 0 ]; then
echo "[ERROR] We pay for $DIFF reserved $RUNNING_INSTANCE_TYPE instance(s) which we don't use (current running $RUNNING_INSTANCE_TYPE's count is $RUNNING_INSTANCE_COUNT while current reserved $RUNNING_INSTANCE_TYPE's count is $RESERVED_INSTANCE_COUNT)"
ERROR="true"
fi
done
if [ $ERROR = "true" ]; then
exit 1
else
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.