jimboobrien
7/24/2017 - 11:44 PM

AWS Bandwidth Usage Report by Instance

AWS Bandwidth Usage Report by Instance

#!/bin/bash

EC2_INSTANCE_ID="`wget -q -O - http://169.254.169.254/latest/meta-data/instance-id || die \"wget instance-id has failed: $?\"`"
test -n "$EC2_INSTANCE_ID" || die 'cannot obtain instance-id'

EC2_AVAIL_ZONE="`wget -q -O - http://169.254.169.254/latest/meta-data/placement/availability-zone || die \"wget availability-zone has failed: $?\"`"
test -n "$EC2_AVAIL_ZONE" || die 'cannot obtain availability-zone'

EC2_REGION="`echo \"$EC2_AVAIL_ZONE\" | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`"

STARTTIME=`date -d "-1 month -$(($(date +%-d)-1)) days" +%Y-%m-%dT00:00:00` #First day of Last Month
ENDTIME=`date -d "-$(($(date +%-d)-1)) days" +%Y-%m-%dT00:00:00` #Last day of Last Month

#echo $EC2_INSTANCE_ID . ' ' . $EC2_AVAIL_ZONE . ' ' . $EC2_REGION

SUM=0

for DATA in `/usr/local/bin/aws cloudwatch get-metric-statistics --metric-name NetworkOut --start-time $STARTTIME --end-time $ENDTIME --period 3600 --namespace AWS/EC2 --statistics Sum --dimensions Name=InstanceId,Value=$EC2_INSTANCE_ID --region $EC2_REGION --output text | awk -F" " '{print $2}'`; do
    SUM=`expr $SUM + ${DATA%.*}` #%.* removes the float stuff
done

echo "$SUM Bytes"
GB=`expr $SUM / 1000 / 1000 / 1000`
echo "$GB Gigabytes"