Monday 23 July 2018

How to test age of an AWS instance in a shell script

How to test age of an AWS instance in a shell script
Here's one way to test age of an AWS (Amazon Web Services) instance in a shell script. The process below does the following:
  • Uses ec2-describe-instances to get instance launch time from Amazon (requires EC2 API Tools)
  • Converts time stamp to syntax suitable for the date command, then uses that to convert AWS launch time to seconds since 1970 format
  • Gets current system time in seconds since 1970 format
  • Calculates instance age in seconds
  • Depending on age, displays it in seconds, hours or days
Function to get launch time from AWS, convert it to seconds and get current time in seconds:
GetTimes()
{
  if [ -z $region ]; then
    echo "ERROR: $FUNCNAME() needs 'region' var, but it's undefined"
  elif [ -z $instance ]; then
    echo "ERROR: $FUNCNAME() needs 'instance' var, but it's undefined"
  else
    LaunchTime=$(ec2-describe-instances --region $region $instance |
                 awk '/^INSTANCE/ {gsub("T"," ",$10); print$10}')
    if [ -z $LaunchTime ]; then
      echo "ERROR: $FUNCNAME() unable to determine 'LaunchTime'"
    else
      LaunchTimeSec=$(date --date="$LaunchTime" +%s)
      CurrentTimeSec=$(date +%s)
    fi
  fi
}
Function to calculate age and determine how to display based on number of seconds:
GetAge()
{
  InstanceAge=$(( $CurrentTimeSec-$LaunchTimeSec ))
  if [ $InstanceAge -lt 60 ]; then
    Age="${InstanceAge}s"
  elif [ $InstanceAge -gt 59 ] && [ $InstanceAge -lt 3600 ]; then
    Age="$(( $InstanceAge/60 ))m"
  elif [ $InstanceAge -gt 3599 ] && [ $InstanceAge -lt 86400 ]; then
    Age="$(( $InstanceAge/60/60 ))h"
  else
    Age="$(( $InstanceAge/60/60/24 ))d"
  fi
}
Example of the above in action:
instance=i-3453aa06 
region=us-west-2
GetTimes
GetAge
echo "instance $instance in $region is $Age old (launched $(date --date="$LaunchTime" +"%F %T %z"))"
Output:
instance i-3453aa06 in us-west-2 is 10h old (launched 2012-12-13 23:25:53 -0800)

0 comments:

Post a Comment