未创建状态检查失败的CloudWatch警报

时间:2020-07-03 01:40:21

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

此代码示例与我用来在CloudWatch中创建CPU,磁盘和内存警报的代码相似。我想为CloudWatch StatusCheckFailed的所有实例创建警报。有人可以告诉我为什么没有创建StatusCheckFailed警报吗?

import boto3, sys

# Create EC2 resourcestr(sys.argv)
ec2 = boto3.resource('ec2')

# Getting all running instances
#instances = ec2.instances.all()

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

# Initialize i_name and i_div variables with instance Name and Costcenter tags
for i in instances:
    i_name = "unnamed"
    for tag in i.tags:
        if tag['Key'] == "Name":
            i_name = tag['Value']
        if tag["Key"] == 'Costcenter':
            i_div = tag['Value']

# List all metrics with namespace as CWAgent, metric-name as Memory % Committed Bytes In Use and partial dimension as instanceid
    listOfMetrics = cw.list_metrics(
        Namespace = '"AWS/EC2"',
        MetricName = 'StatusCheckFailed',
        Dimensions = [
            {
                'Name': 'InstanceId',
                'Value': i.id
            }
        ]
    )

# Check if StatusCheckFailed metrics exists
    if listOfMetrics['Metrics'] != []:
        # Check the state of the instance to see if it is running
        if i.state["Name"] == "running" :
            # Create the alarm
            for metric in listOfMetrics['Metrics']:
                putAlarm = cw.put_metric_alarm (
                    AlarmName = i_div + "-" + i_name + "-(" + i.id + ")-" + "StatusCheckFailed",
                    AlarmDescription = 'Status check for %s %s' % (i.id, i_name),
                    ComparisonOperator = "GreaterThanOrEqualToThreshold",
                    ActionsEnabled = True,
                    AlarmActions = [alarm],
                    Statistic = "Maximum",
                    EvaluationPeriods = 2,
                    Threshold = 1.0,
                    Period = 60,
                    Dimensions = [{
                        'Name': 'InstanceId', 
                        'Value': i.id
                        }
                    ]
                )

1 个答案:

答案 0 :(得分:1)

Namespace ='AWS / EC2'中也包含双引号。Namespace ='“ AWS / EC2”'在使代码统一时,我将所有字符串都设置在单引号中,以替换双引号。对于命名空间字符串,我忽略了删除双引号。该脚本现在正在按预期运行。