首页 > 解决方案 > 如何在 CloudFormation yaml 模板中从 CloudWatch 为 CloudFront 设置警报?

问题描述

我想设置警报,以防 CloudWatch 在 CloudFront 上发生错误。

在控制台中,我将直接创建一个警报,如果TotalErrorRate大于 0,它将向我发送电子邮件。这工作正常。

但现在我想在 CloudFormation 的 yaml 模板文件中设置相同的设置。我无法确定相应参数的正确值。我的文件目前看起来像这样:

  # CloudWatch
  CloudFrontTotalErrorRateAlarm:
    Type: "AWS::CloudWatch::Alarm"
    Properties:
      ActionsEnabled: Boolean
      AlarmActions:
        - String
      AlarmDescription: "Trigers an alarm if there is any error (e.g. 4xx,5xx)"
      AlarmName: "MyApiTotalErrorRate"
      ComparisonOperator: GreaterThanThreshold
      Dimensions:
        - Dimension
      EvaluationPeriods: "1"
      ExtendedStatistic: String
      InsufficientDataActions:
        - String
      MetricName: TotalErrorRate
      Namespace: AWS/CloudFront
      OKActions:
        - String
      Period: 60
      Statistic: String
      Threshold: 0
      TreatMissingData: String
      Unit: String

对于某些参数,我可以弄清楚实际值可能是多少。但对于其他人来说,我基本上不知道我应该输入什么,以便 AWS 会在发生错误时向我发送电子邮件。以下参数为缺失值:

标签: amazon-web-servicesamazon-cloudformationamazon-cloudwatchamazon-cloudwatch-metrics

解决方案


首先,您需要SNS Topic使用您的电子邮件地址创建一个订阅者:

EscalationTopic:
  Type: AWS::SNS::Topic

EscalationTopicEmailSubscriber:
    Type: AWS::SNS::Subscription
    Properties:
      Endpoint: john.doe@example.com
      Protocol: email
      TopicArn: !Ref EscalationTopic

作为第二步,您需要向DistributionIdCF 模板提供 (只要 Distribution 不是 CF 模板的一部分):

Parameters:
  DistributionId:
    Type: String

最后,您必须将所有内容连接在一起并按CloudWatch Alarm以下方式配置:

CloudFrontTotalErrorRateAlarm:
  Type: AWS::CloudWatch::Alarm
  Properties:
    Namespace: AWS/CloudFront
    MetricName: TotalErrorRate
    Dimensions:
      - Name: DistributionId
        Value: !Ref DistributionId
    Statistic: Sum
    Period: 60
    EvaluationPeriods: 1
    ComparisonOperator: GreaterThanOrEqualToThreshold
    Threshold: 1
    AlarmActions:
      - !Ref EscalationTopic

“最终”的 CF 模板可能如下所示:

AWSTemplateFormatVersion: 2010-09-09
Parameters:
  DistributionId:
    Type: String
Resources:
  EscalationTopic:
    Type: AWS::SNS::Topic

  EscalationTopicEmailSubscriber:
      Type: AWS::SNS::Subscription
      Properties:
        Endpoint: john.doe@example.com
        Protocol: email
        TopicArn: !Ref EscalationTopic

  CloudFrontTotalErrorRateAlarm:
    Type: AWS::CloudWatch::Alarm
    Properties:
      Namespace: AWS/CloudFront
      MetricName: TotalErrorRate
      Dimensions:
        - Name: DistributionId
          Value: !Ref DistributionId
      Statistic: Sum
      Period: 60
      EvaluationPeriods: 1
      ComparisonOperator: GreaterThanOrEqualToThreshold
      Threshold: 1
      AlarmActions:
        - !Ref EscalationTopic

推荐阅读