how to find out when an EC2 instance was last stopped

Viewed 7305

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.

4 Answers

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) |
+-------------------+---------------------+---------+------------------------------------------+
Related