简体   繁体   中英

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 .

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)

Code:

import boto3
from prettytable import PrettyTable

cli = boto3.client('ec2')
resp = cli.describe_instances(
    Filters=[
        {
            'Name': 'instance-state-name',
            'Values': [
                'stopped',
            ]
        },
    ],
    MaxResults=1000,
)

table = PrettyTable()
table.field_names = ["Name", "ID", "State", "Reason"]

for r in resp["Reservations"]:
    for i in r["Instances"]:
        name = ''
        for t in i["Tags"]:
            if t["Key"] == "Name":
                name = t["Value"]

        table.add_row([name, i["InstanceId"], i["State"]["Name"],
                       i["StateTransitionReason"]])

print(table.get_string(sortby="Reason"))

Output:

+-------------------+---------------------+---------+------------------------------------------+
|       Name        |          ID         |  State  |                  Reason                  |
+-------------------+---------------------+---------+------------------------------------------+
| server-name-tag-1 | i-0a12b3056c789012a | stopped | User initiated (2017-02-27 20:20:00 GMT) |
| server-name-tag-2 | i-1b12b3956c789012b | stopped | User initiated (2018-02-27 20:20:00 GMT) |
| server-name-tag-3 | i-2c12b3856c789012c | stopped | User initiated (2019-02-27 20:20:00 GMT) |
| server-name-tag-4 | i-3d12b3756c789012d | stopped | User initiated (2020-02-27 20:20:00 GMT) |
+-------------------+---------------------+---------+------------------------------------------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM