使用CloudWatch警报启动ec2实例

0

【以下的问题经过翻译处理】 我需要通过 Python 代码启动 ec2 实例。目前我使用启动模板启动它们。我需要为每个实例创建一个CloudWatch告警,但我不知道如何将告警分配给启动模板(如果可能的话)。

警报的功能是,停止处于非活动状态的实例。

profile picture
专家
已提问 5 个月前12 查看次数
1 回答
0

【以下的回答经过翻译处理】 你不能直接将CloudWatch告警分配给启动模板。但是,你可以在使用Python的boto3库启动实例后再创建告警。以下是使用启动模板启动EC2实例,然后为每个实例创建CloudWatch告警的逐步指南:

  1. 如果尚未安装boto3库,请先安装它:
pip install boto3

  1. 使用启动模板启动EC2实例:
import boto3

ec2 = boto3.client('ec2')

response = ec2.run_instances(
    LaunchTemplate={
        'LaunchTemplateName': 'your-launch-template-name',
        'Version': 'your-launch-template-version'
    },
    MinCount=1,
    MaxCount=1
)

instance_id = response['Instances'][0]['InstanceId']
print(f'Launched instance with ID: {instance_id}')

  1. 为启动的实例创建CloudWatch告警:
import boto3

cloudwatch = boto3.client('cloudwatch')

# 使用相应的指标替换“your-instance-idle-metric”和所需运算符替换“your-comparison-operator”(例如'LessThanOrEqualToThreshold')
response = cloudwatch.put_metric_alarm(
    AlarmName=f'IdleAlarm-{instance_id}',
    ComparisonOperator='your-comparison-operator',
    EvaluationPeriods=1,
    MetricName='your-instance-idle-metric',
    Namespace='AWS/EC2',
    Period=300,
    Statistic='SampleCount',
    Threshold=1.0,
    ActionsEnabled=True,
    AlarmActions=[
        'arn:aws:automate:your-region:ec2:stop'  # 将'your-region'替换为适当的AWS区域
    ],
    AlarmDescription=f'Alarm for stopping idle instance {instance_id}',
    Dimensions=[
        {
            'Name': 'InstanceId',
            'Value': instance_id
        },
    ],
    Unit='Seconds',
    TreatMissingData='breaching'
)

print(f'Created alarm for instance {instance_id}')


上面的代码使用启动模板启动 EC2 实例,然后为启动的实例创建 CloudWatch 告警。当实例处于非活动状态时,警报将根据指定的指标、比较运算符和阈值将其停止。

profile picture
专家
已回答 5 个月前

您未登录。 登录 发布回答。

一个好的回答可以清楚地解答问题和提供建设性反馈,并能促进提问者的职业发展。

回答问题的准则