David
David

Reputation: 1569

Is there a way to determine how long has an Amazon AWS EC2 Instance been running for?

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?

Upvotes: 6

Views: 7671

Answers (2)

garnaat
garnaat

Reputation: 45846

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.

Upvotes: 5

avip
avip

Reputation: 1465

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

Upvotes: 1

Related Questions