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
.
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).
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With