Checking STOP time of EC2 instance with boto3

5.5k views Asked by At

Python 2.7 Boto3

I'm trying to get a timestamp of when the instance was stopped OR the time the last state transition took place OR a duration of how long the instance has been in the current state.

My goal is to test if an instance has been stopped for x hours.

For example,

instance = ec2.Instance('myinstanceID')
if int(instance.state['Code']) == 80:
    stop_time = instance.state_change_time() #Dummy method.

Or something similar to that.

I see that boto3 has a launch_time method. And lots of ways to analyze state changes using state_transition_reason and state_reason but I'm not seeing anything regarding the state transition timestamp.

I've got to be missing something.

Here is the Boto3 docs for Instance "state" methods...

state
(dict) --

The current state of the instance.

Code (integer) --

The low byte represents the state. The high byte is an opaque internal value and should be ignored.

0 : pending
16 : running
32 : shutting-down
48 : terminated
64 : stopping
80 : stopped
Name (string) --

The current state of the instance.


state_reason
(dict) --

The reason for the most recent state transition.

Code (string) --

The reason code for the state change.

Message (string) --

The message for the state change.

Server.SpotInstanceTermination : A Spot instance was terminated due to an increase in the market price.
Server.InternalError : An internal error occurred during instance launch, resulting in termination.
Server.InsufficientInstanceCapacity : There was insufficient instance capacity to satisfy the launch request.
Client.InternalError : A client error caused the instance to terminate on launch.
Client.InstanceInitiatedShutdown : The instance was shut down using the shutdown -h command from the instance.
Client.UserInitiatedShutdown : The instance was shut down using the Amazon EC2 API.
Client.VolumeLimitExceeded : The limit on the number of EBS volumes or total storage was exceeded. Decrease usage or request an increase in your limits.
Client.InvalidSnapshot.NotFound : The specified snapshot was not found.


state_transition_reason
(string) --

The reason for the most recent state transition. This might be an empty string.
2

There are 2 answers

5
helloV On BEST ANSWER

The EC2 instance has an attribute StateTransitionReason which also has the time the transition happened. Use Boto3 to get the time the instance was stopped.

print status['StateTransitionReason']
...
User initiated (2016-06-23 23:39:15 GMT)

The code below prints stopped time and current time. Use Python to parse the time and find the difference. Not very difficult if you know Python.

import boto3
import re

client = boto3.client('ec2')
rsp = client.describe_instances(InstanceIds=['i-03ad1f27'])
if rsp:
  status = rsp['Reservations'][0]['Instances'][0]
  if status['State']['Name'] == 'stopped':
    stopped_reason = status['StateTransitionReason']
    current_time = rsp['ResponseMetadata']['HTTPHeaders']['date']
    stopped_time = re.findall('.*\((.*)\)', stopped_reason)[0]
    print 'Stopped time:', stopped_time
    print 'Current time:', current_time

Output

Stopped time: 2016-06-23 23:39:15 GMT
Current time: Tue, 20 Dec 2016 20:33:22 GMT
0
John Rotenstein On

You might consider using AWS Config to view the configuration history of the instances.

AWS Config is a fully managed service that provides you with an AWS resource inventory, configuration history, and configuration change notifications to enable security and governance

The get-resource-config-history command can return information about an instance, so it probably has Stop & Start times. It will take a bit of parsing to extract the details.