David Perera
David Perera

Reputation: 33

How to set alarm in metric filter using CloudFormation

How to create alarm for metric filter and connect SNS topic.

My task is:

  1. Create SNS topic and email subscription
  2. Create CloudWatch log group
  3. Create metric filter for that CloudWatch log group and create alarm and connect SNS topic
AWSTemplateFormatVersion: "2010-09-09"
#Parameters:
 #EmailAddress:
  #Type: String
  #Description: The email address to use for alarm notifications.

Resources:
 # Create SNS and email subscription
 MySNSTopic:
  Type: AWS::SNS::Topic
  Properties:
    Subscription:
    - Endpoint: "[email protected]"
      Protocol: email
   
 # Create CloudWatch log group
 snstopic: 
  Type: AWS::Logs::LogGroup
  DependsOn: MySNSTopic
  Properties: 
    RetentionInDays: 7
  
 # Create metric filter
 UnauthorizedApiCalls: 
  Type: AWS::Logs::MetricFilter
  DependsOn: snstopic
  Properties: 
    LogGroupName: 
      Ref: "snstopic"
    FilterPattern: '{($.errorCode="*UnauthorizedOperation") || ($.errorCode="AccessDenied*")}'
    MetricTransformations: 
      - MetricValue: "1"
        MetricNamespace: "unauthorized-api-calls"
        MetricName: "LogMetrics"
  
 # Create alarm
 UnauthorizedApiCallsAlarm:
  Type: AWS::CloudWatch::Alarm
  DependsOn: UnauthorizedApiCalls
  Properties:
    AlarmName: UnauthorizedApiCallsAlarm
    AlarmActions: !Ref snstopic
    MetricName: UnauthorizedApiCalls
    Namespace: LogMetrics
    ComparisonOperator: GreaterThanOrEqualToThreshold
    EvaluationPeriods: '1'
    Period: '5'
    Statistic: Sum
    Threshold: '1'
    TreatMissingData: breaching

Upvotes: 1

Views: 2988

Answers (1)

shimo
shimo

Reputation: 2285

Try this one. According to the documentation, the type of AlarmActions is List of String.

# Create alarm
UnauthorizedApiCallsAlarm:
 Type: AWS::CloudWatch::Alarm
 DependsOn: UnauthorizedApiCalls
 Properties:
   AlarmName: UnauthorizedApiCallsAlarm
   AlarmActions: 
   - !Ref snstopic
   MetricName: UnauthorizedApiCalls
   Namespace: LogMetrics
   ComparisonOperator: GreaterThanOrEqualToThreshold
   EvaluationPeriods: '1'
   Period: '5'
   Statistic: Sum
   Threshold: '1'
   TreatMissingData: breaching

Upvotes: 2

Related Questions