Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to find out when an EC2 instance was last stopped

Is there a way to easily find out when an EC2 instance was last stopped? I am able to get the launch time from ec2.get_only_instances() by looking at the launch_time variable. However, it doesn't look as if the stop time is stored in any of the metadata.

We will probably be implementing this using the rc#.d scripts for shutdown, but I am just wondering if I could get that information via boto.

like image 230
Nova Avatar asked Dec 31 '13 08:12

Nova


3 Answers

You could use the reason variable of stopped instances:

import boto.ec2
conn = boto.ec2.connect_to_region("eu-west-1")
reservations = conn.get_all_instances()
for r in reservations:
    for i in r.instances:
        if i.state == 'stopped':
            print "%s [%s] %s" % (i.id, i.state, i.reason)

Output:

i-11223344 [stopped] User initiated (2013-12-20 13:59:08 GMT)

This works also for terminated instances (as long as they are still displayed).

like image 58
andpei Avatar answered Oct 29 '22 11:10

andpei


I think that better practice would be:

import boto.ec2
conn = boto.ec2.connect_to_region("eu-west-1")
reservations = conn.get_all_instances()
instances = []
for reservation in reservations:
    for instance in reservation.instances:
        if "Name" in instance.tags.keys():
            instances.append((instance.tags["Name"],
                              instance.get_console_output().timestamp))

You can also replace the if and get whatever you want, but instance.get_console_output().timestamp is the right way to get instance's stopped timestamp

like image 27
Yonatan Kiron Avatar answered Oct 29 '22 11:10

Yonatan Kiron


Look at this please,it is returning timestamp within ec2 name which have stopped at aws and its color red. Note that set an aws profile environment which have contains credential before run it.

import boto.ec2    

class i_color:
  red   = '\033[31m'
  reset = '\033[0m'

def name(i):
  if 'Name' in i.tags:
    n = i.tags['Name']
    n = i_color.red + n + i_color.reset
  return n

conn = boto.ec2.connect_to_region("us-east-1")
reservations = conn.get_all_instances()
for r in reservations:
    for i in r.instances:
        if i.state == 'stopped':
           print "%s [%s] %s" % (name(i),i.state,i.reason)

Sample output:

test-ec2-temp05 [stopped] User initiated (2016-08-02 09:00:43 GMT)
like image 32
Uğur Engin Avatar answered Oct 29 '22 10:10

Uğur Engin