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.
答案 0 :(得分:2)
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
答案 1 :(得分:0)
您可以考虑将 AWS Config 用于view the configuration history个实例。
AWS Config 是一项完全托管服务,可为您提供AWS资源清单,配置历史记录以及配置更改通知,以启用安全性和治理
get-resource-config-history
命令可以返回有关实例的信息,因此它可能有Stop&开始时间。需要进行一些解析才能提取细节。