python-使用boto3检查EC2实例的停止时间

Python 2.7
Boto3

我正在尝试获取实例何时停止或上一次状态转换发生的时间或实例一直处于当前状态的持续时间的时间戳.

我的目标是测试实例是否已停止x小时.

例如,

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

或类似的东西.

我看到boto3有一个launch_time方法.还有很多使用state_transition_reason和state_reason分析状态变化的方法,但是我看不到任何有关状态转换时间戳的信息.

我一定要错过一些东西.

这是实例“状态”方法的Boto3文档…

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.

解决方法:

EC2实例具有StateTransitionReason属性,该属性还具有发生过渡的时间.使用Boto3获取实例停止的时间.

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

下面的代码显示停止时间和当前时间.使用Python解析时间并找出差异.如果您了解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

输出量

Stopped time: 2016-06-23 23:39:15 GMT
Current time: Tue, 20 Dec 2016 20:33:22 GMT
上一篇:Boto3访问S3的基本用法


下一篇:s5cmd,比s3cmd更快的s3协议客户端