如何一次使用Boto3创建多个CloudWatch警报

时间:2018-08-31 06:07:03

标签: python amazon-web-services amazon-ec2 boto3 amazon-cloudwatch

我想创建〜267个Cloudwatch警报,手动过程是如此可悲,有人可以指导我使用Boto3脚本,以便我可以一次设置所有警报。

谢谢:)

import boto3

# Create CloudWatch client
cloudwatch = boto3.client('cloudwatch')

# Create alarm
cloudwatch.put_metric_alarm(
    AlarmName='Web_Server_CPU_Utilization',
    ComparisonOperator='GreaterThanThreshold',
    EvaluationPeriods=1,
    MetricName='CPUUtilization',
    Namespace='AWS/EC2',
    Period=60,
    Statistic='Average',
    Threshold=70.0,
    ActionsEnabled=False,
    AlarmDescription='Alarm when server CPU exceeds 70%',
    Dimensions=[
        {
          'Name': 'InstanceId',
          'Value': 'i-xxxxxxxxxx'
        },
    ],
    Unit='Seconds'
)

1 个答案:

答案 0 :(得分:0)

假设您要为不同的EC2实例添加CloudWatch警报,只需将实例ID放在列表中,然后在该列表上进行迭代以创建警报。看起来像:

import boto3

cloudwatch = boto3.client('cloudwatch')

ec2_instances = [
    'i-xxxxxxxxx1',
    'i-xxxxxxxxx2',
    'i-xxxxxxxxx3'
]

for ec2_instance in ec2_instances:
    cloudwatch.put_metric_alarm(
        AlarmName='Web_Server_CPU_Utilization_%s' % ec2_instance,
        ComparisonOperator='GreaterThanThreshold',
        EvaluationPeriods=1,
        MetricName='CPUUtilization',
        Namespace='AWS/EC2',
        Period=60,
        Statistic='Average',
        Threshold=70.0,
        ActionsEnabled=False,
        AlarmDescription='Alarm when server CPU exceeds 70%',
        Dimensions=[
            {
              'Name': 'InstanceId',
              'Value': ec2_instance
            },
        ],
        Unit='Seconds'
    )