2014-02-18 89 views
1

我一直無法找到一個簡單的例子,告訴我如何使用boto來使用鬧鐘來終止Amazon EC2實例(不使用AutoScaling)。我想在10分鐘內終止CPU使用率小於1%的特定實例。如何設置警報來終止使用boto的EC2實例?

這是我到目前爲止已經試過:

import boto.ec2 
import boto.ec2.cloudwatch 
from boto.ec2.cloudwatch import MetricAlarm 

conn = boto.ec2.connect_to_region("us-east-1", aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY) 
cw = boto.ec2.cloudwatch.connect_to_region("us-east-1", aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY) 

reservations = conn.get_all_instances() 
for r in reservations: 
    for inst in r.instances: 
     alarm = boto.ec2.cloudwatch.MetricAlarm(name='TestAlarm', description='This is a test alarm.', namespace='AWS/EC2', metric='CPUUtilization', statistic='Average', comparison='<=', threshold=1, period=300, evaluation_periods=2, dimensions={'InstanceId':[inst.id]}, alarm_actions=['arn:aws:automate:us-east-1:ec2:terminate']) 
     cw.put_metric_alarm(alarm) 

不幸的是它給了我這個錯誤:

dimensions={'InstanceId':[inst.id]}, alarm_actions=['arn:aws:automate:us-east-1:ec2:terminate']) TypeError: init() got an unexpected keyword argument 'alarm_actions'

我敢肯定,這是一些簡單的我失蹤。

此外,我沒有使用CloudFormation,因此我無法使用AutoScaling功能。這是因爲我不希望警報在整個組中使用度量標準,而只是針對特定實例使用度量標準,並且僅終止該特定實例(而不是該組中的任何實例)。

在此先感謝您的幫助!

回答

1

警報操作不通過維度傳遞,而是作爲屬性添加到您正在使用的MetricAlarm對象。在你的代碼,你需要做到以下幾點:

alarm = boto.ec2.cloudwatch.MetricAlarm(name='TestAlarm', description='This is a test alarm.', namespace='AWS/EC2', metric='CPUUtilization', statistic='Average', comparison='<=', threshold=1, period=300, evaluation_periods=2, dimensions={'InstanceId':[inst.id]}) 
alarm.add_alarm_action('arn:aws:automate:us-east-1:ec2:terminate') 
cw.put_metric_alarm(alarm) 

您還可以看到博託文檔在這裏:

http://docs.pythonboto.org/en/latest/ref/cloudwatch.html#module-boto.ec2.cloudwatch.alarm

+0

現在我得到的錯誤:'cw.put_metric_alarm(報警) 文件「/usr/lib/python2.6/site-packages/boto-2.0-py2.6.egg/boto/ec2/cloudwatch/__init__.py」,第545行,在put_metric_alarm中 'Dimensions.member。%s 。%s') 文件「/usr/lib/python2.6/site-packages/boto-2.0-py2.6.egg/boto/ec2/cloudwatch/__init__.py」,第237行,在build_list_params中 參數[標籤%i] =項目 TypeError:沒有足夠的格式字符串參數 – Chewy734

+0

原來我使用boto 2.0,這不是最新版本。一旦我更新到2.25.0,它使用我原來的方式運行良好。雖然謝謝! – Chewy734

+0

那麼,我的答案也能工作嗎? – Rico