【问题标题】:How do I set an alarm to terminate an EC2 instance using boto?如何设置警报以使用 boto 终止 EC2 实例?
【发布时间】:2014-03-18 19:10:13
【问题描述】:

我一直找不到一个简单的示例来展示如何使用 boto 通过警报终止 Amazon EC2 实例(不使用 AutoScaling)。我想终止 CPU 使用率低于 1% 的特定实例 10 分钟。

这是我迄今为止尝试过的:

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() 得到了一个意外的关键字参数 'alarm_actions'

我确定这是我缺少的一些简单的东西。

另外,我没有使用 CloudFormation,因此无法使用 AutoScaling 功能。这是因为我不希望警报在整个组中使用指标,而仅针对特定实例,并且仅终止该特定实例(而不是该组中的任何实例)。

提前感谢您的帮助!

【问题讨论】:

    标签: amazon-ec2 alarm boto terminate amazon-cloudwatch


    【解决方案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)
    

    您也可以在此处查看 boto 文档:

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

    【讨论】:

    • 现在我收到错误消息:cw.put_metric_alarm(alarm) File "/usr/lib/python2.6/site-packages/boto-2.0-py2.6.egg/boto/ec2/cloudwatch/__init__.py", line 545, in put_metric_alarm 'Dimensions.member.%s.%s') File "/usr/lib/python2.6/site-packages/boto-2.0-py2.6.egg/boto/ec2/cloudwatch/__init__.py", line 237, in build_list_params params[label % i] = item TypeError: not enough arguments for format string
    • 原来我使用的是boto 2.0,它不是最新版本。一旦我更新到 2.25.0,它就可以按照我最初的方式正常工作。不过谢谢!
    • 为了将来参考,这里列出了可用的自动警报操作:docs.aws.amazon.com/AmazonCloudWatch/latest/DeveloperGuide/…
    • @Rico 就我而言,EC2 实例位于 EMR 的实例组下。我可以通过引导操作在给定的 instanceId 和“CPUUtilization”(无论你提到什么)上创建警报。但是,在引导时,给定的 instanceId 不存在维度。你能为我的用例推荐一些解决方案吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-14
    相关资源
    最近更新 更多