如何设置警报以使用Boto终止EC2实例

如何设置警报以使用Boto终止EC2实例

本文介绍了如何设置警报以使用Boto终止EC2实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have been unable to find a simple example which shows me how to use boto to terminate an Amazon EC2 instance using an alarm (without using AutoScaling). I want to terminate the specific instance that has a CPU usage less than 1% for 10 minutes.

这是到目前为止我尝试过的操作:

Here is what I've tried so far:

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)

不幸的是,它给了我这个错误:

Unfortunately it gives me this error:

我确定这很简单我不见了。

I'm sure it's something simple I'm missing.

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

Also, I am not using CloudFormation, so I cannot use the AutoScaling feature. This is because I don't want the alarm to use a metric across the entire group, rather only for a specific instance, and only terminate that specific instance (not any instance in that group).

谢谢您的帮助!

推荐答案

警报操作不会通过尺寸传递,而是添加为您正在使用的MetricAlarm对象的属性。在您的代码中,您需要执行以下操作:

The alarm actions are not passed through dimensions but rather added as an attribute to the MetricAlarm object that you are using. In your code you need to do the following:

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文档中看到以下内容:

You can also see in the boto documentation here:

这篇关于如何设置警报以使用Boto终止EC2实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-28 02:15