如何用Python3通过boto3创建带多指标及数学表达式的CloudWatch告警
基于boto3创建含多指标、数学表达式的CloudWatch告警示例
该实现可针对指定自动扩缩容组创建自定义CloudWatch告警,函数入参asg_name为目标自动扩缩容组的名称,具体实现代码如下:
import boto3 cloudwatch = boto3.client('cloudwatch', region_name="eu-west-1") def create_cloudwatch_alarm(asg_name): cloudwatch.put_metric_alarm( ActionsEnabled=True, AlarmName=asg_name, ComparisonOperator='GreaterThanThreshold', DatapointsToAlarm=3, EvaluationPeriods=3, Metrics=[{'Expression': 'IF(m1 > m2, 1, 0)', 'Id': 'e2', 'Label': 'Compare Running vs desired capacity', 'ReturnData': True}, {'Id': 'm1', 'MetricStat': {'Metric': {'Dimensions': [{'Name': 'AutoScalingGroupName', 'Value': asg_name}], 'MetricName': 'GroupDesiredCapacity', 'Namespace': 'AWS/AutoScaling'}, 'Period': 300, 'Stat': 'Average'}, 'ReturnData': False}, {'Id': 'm2', 'MetricStat': {'Metric': {'Dimensions': [{'Name': 'AutoScalingGroupName', 'Value': asg_name}], 'MetricName': 'GroupInServiceInstances', 'Namespace': 'AWS/AutoScaling'}, 'Period': 300, 'Stat': 'Average'}, 'ReturnData': False}], Threshold=0.1, TreatMissingData='missing' )
- 告警核心配置说明:
- 评估周期设置:单指标采集周期为5分钟,整体评估周期数为3,需要连续3个评估周期内的有效数据点满足判定条件才会触发告警
- 多指标比对逻辑:同时拉取自动扩缩容组的两个核心监控指标——GroupDesiredCapacity(组期望容量)、GroupInServiceInstances(组内正常在运实例数),通过数学表达式
IF(m1 > m2, 1, 0)做判断,当期望容量大于实际在运实例数时,表达式输出值为1 - 触发判定:采用大于阈值的比较逻辑,当表达式输出值超过0.1的阈值时即满足触发条件
- 数据容错设置:针对缺失数据按missing规则处理,拉取不到指标数据时不会误触发告警状态
内容的提问来源于stack exchange,提问作者mohammed arbib
相关产品推荐
相关产品推荐

