---
# Define CloudWatch alert based on aggregate metric using metric math 

AWSTemplateFormatVersion: '2010-09-09'
Description: Alert when EFS throughput reaches 75% of maximum

Parameters:

  EFSid:
    Description: EFS filesystem ID
    Type: String
    Default: fs-12345678
 
  SNStopic:
    Description: SNS topic for Cloudwatch alerts (leave empty to disable alerting)
    Type: String
    Default: ""

Conditions:
  EnableCloudwatch: !Not [!Equals [!Ref SNStopic, "" ]]
 
Resources:

  HighEFSThroughput:
    Type: AWS::CloudWatch::Alarm
    Condition: EnableCloudwatch
    Properties:
      AlarmActions:
      - !Sub "arn:aws:sns:${AWS::Region}:${AWS::AccountId}:${SNStopic}"
      OKActions:
      - !Sub "arn:aws:sns:${AWS::Region}:${AWS::AccountId}:${SNStopic}"
      AlarmDescription: EFS throughput utilization is over 75% of maximum
      ComparisonOperator: GreaterThanThreshold
      Threshold: 75
      TreatMissingData: ignore
      EvaluationPeriods: 5
      Metrics:
        - Id: m1
          MetricStat:
            Metric:
              Dimensions:
                - Name: FileSystemId
                  Value: !Ref EFSid
              MetricName: MeteredIOBytes
              Namespace: AWS/EFS
            Period: 60
            Stat: Sum
          ReturnData: False
        - Id: m2
          MetricStat:
            Metric:
              Dimensions:
                - Name: FileSystemId
                  Value: !Ref EFSid
              MetricName: PermittedThroughput
              Namespace: AWS/EFS
            Period: 60
            Stat: Sum
          ReturnData: False
        - Id: e1
          Expression: m1/PERIOD(m1)
          Label: Throughput bytes/s
          ReturnData: False
        - Id: e4
          Expression: e1*100/m2
          Label: Throughput utilization (%)
          ReturnData: True

#
# Notice that Metrics Id's must beging with lower-case letter.
# Non-compliant Id's produce this rather cryptic error message:
#
# Invalid metrics list (Service: AmazonCloudWatch; Status Code: 400;
# Error Code: ValidationError; Request ID: 11111111-1234-5678-abcd-ab1234567890; Proxy: null)
#