5

I am looking for a way to programmatically kill long running AWS EC2 Instances.

I did some googling around but I don't seem to find a way to find how long has an instance been running for, so that I then can write a script to delete the instances that have been running longer than a certain time period...

Anybody dealt with this before?

David
  • 1,469
  • 5
  • 33
  • 51

2 Answers2

4

The EC2 service stores a LaunchTime value for each instance which you can find by doing a DescribeInstances call. However, if you stop the instance and then restart it, this value will be updated with the new launch time so it's not really a reliable way to determine how long the instance has been running since it's original launch.

The only way I can think of to determine the original launch time would be to use CloudTrail (assuming you have it enabled for your account). You could search CloudTrail for the original launch event and this would have an EventTime associated with it.

garnaat
  • 44,310
  • 7
  • 123
  • 103
1

I noticed the cron tag on your question so maybe you can use this Bash script:

UPTIME=`uptime | awk {print $3}`

# Reboot if uptime longer than 180 days (6 months)
if [ $UPTIME -gt 180 ]
then
    # Whatever you want to do here...
fi

If you want more granular control you can also get the uptime in seconds from /proc/uptime using something like this:

UPTIME=$(awk -F. '{print $1}' /proc/uptime)

Note {print $2} will give you idle-time in seconds

avip
  • 1,445
  • 13
  • 14
  • I take it, your answer works only when within the ec2 instance itself. What I am after is any metadata that I can get from amazon to tell me at least the time when the EC2 instance got created. – David Mar 15 '16 at 18:44
  • Yes, this is aimed at cron on the ec2 instance itself. You want to be able to get that metadata on some other "supervisor" machine and be able to take action from there? – avip Mar 15 '16 at 18:50