2016-12-19 10 views
1

Python 2.7 Boto3Проверка времени СТОП экземпляра EC2 с boto3

Я пытаюсь получить временную метку, когда экземпляр был остановлен или время последнего перехода состояния имели место, или продолжительность, как долго экземпляр находится в текущем состоянии.

Моя цель - проверить, был ли экземпляр остановлен на х часов.

Например,

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

Или что-то похожее на это.

Я вижу, что boto3 имеет метод . И множество способов анализа изменений состояния с использованием 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. 

ответ

1

Экземпляр 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 
0

Вы могли бы рассмотреть возможность использования AWS Config в view the configuration history из экземпляров.

AWS Config является полностью управляемый сервис, который предоставляет вам с описью AWS ресурсов, истории конфигурации и уведомлений об изменении конфигурации для включения безопасности и управления

Команда get-resource-config-history может возвращать информацию о экземпляре, поэтому он, вероятно, имеет Stop & Время начала. Для извлечения деталей потребуется немного разбора.