Blog |Follow Nick on Twitter| About
 

The free monitoring you get with Amazon CloudWatch is pretty sweet, graphs are cool but gauges are cooler!

To get this working I'm having to run a bash script via cron every 5minutes which gets the max CPU usage from AWS and then downloads an image from the google charts API, I think the result is pretty snazzy!

Example Gauge

Before trying to run this on your machine you will need the CloudWatch API Tools installed.

I'll run though my bash script... to start with I need some date and time variables to work with:

1
2
3
4
5
#!/bin/bash
# Setup some Time Variables
NowMins=`date "+%M"`
NowHrs=`date "+%H"`
Today=`date "+%Y-%m-%d"`

The free cloudwatch tier gives you five minute samples, I have seen that the output is updated every 10 minutes, so I'll take 10 away from the current minutes to get the last "5" minute result from cloudwatch.... it seems like odd logic but it does work... honest!

1
2
3
#!/bin/bash
# The last five minute reading is avilable every ten mintues
FiveMinsAgo=$(($NowMins - 10))

We then need to fix the result of FiveMinsAgo since if the time now is 1minute past the current hour taking away ten will give a negative number rather than 51 minutes past the previous hour.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#!/bin/bash
# If our calcualtion is a negative number correct hours and minutes
if [ $FiveMinsAgo -lt 0 ]
then
    FiveMinsAgo=$(($FiveMinsAgo + 60))
    NowHrs=$(($NowHrs - 1))
fi

# Re-Apply leading zero that gets dropped by calculations
if [ $FiveMinsAgo -lt 10 ]
then
        FiveMinsAgo="0"$FiveMinsAgo
fi

Once that's all sorted, we can format a StartTime option for the API tools and make the request...

1
2
3
4
5
6
#!/bin/bash
#Formate Start Time for API Tools
StartTime=$Today"T"$NowHrs":"$FiveMinsAgo":00.000Z"

# Get Results from API Tools
Result=`mon-get-stats CPUUtilization --namespace "AWS/EC2" --statistics "Maximum"  --dimensions "InstanceId=i-123456" --start-time $StartTime `

In the above you will need to change i-123456 with your Instance ID... as you can see I have stored the result as a variable which we cut it up below using awk to leave only the CPU % of the instance for use with google charts.

1
2
3
4
5
6
#!/bin/bash
Percent=`echo $Result | awk '{print $3}'`

Chart="https://chart.googleapis.com/chart?chs=200x125&cht=gom&chd=t:"$Percent"&chl="$Percent"%&chco=00AA0066,FF804066,AA000066&chf=bg,s,FFFFFF00"

curl $Chart -o cpu.png

The final piece of the puzzle above is downloading the chart from google using curl, which results in cpu.png.

I then save this image on my webserver and create my own status dashboard! I've attached a copy of the script for your download if you wish to re-create the same thing.

Happy Gauging!

 

 
Nick Bettison ©