AWSTemplateFormatVersion: '2010-09-09'
Description: 'CloudFormation template for Redshift Event Subscription with SNS Topic'

Parameters:
  MonitorAllClusters:
    Type: String
    Description: 'Monitor all clusters (true) or specific clusters (false)'
    AllowedValues: 
      - 'true'
      - 'false'
    Default: 'false'

  ClusterIdentifier:
    Type: String
    Description: 'The identifier of the Redshift cluster'
    Default: ''
  
  EmailAddress:
    Type: String
    Description: 'Email address to receive notifications'
    
  EventSubscriptionName:
    Type: String
    Description: 'Name for the event subscription'

  SeverityLevel:
    Type: String
    Description: 'Choose severity level for notifications'
    AllowedValues:
      - 'ERROR'
      - 'INFO'
    Default: 'ERROR' 

Conditions:
  IsSpecificCluster: !Equals 
    - !Ref MonitorAllClusters
    - 'false'
  
Resources:
  # Create SNS Topic
  RedshiftEventTopic:
    Type: 'AWS::SNS::Topic'
    Properties:
      DisplayName: 'Redshift-Events-Topic'
      TopicName: !Sub '${EventSubscriptionName}-topic'

  # Create SNS Topic Subscription
  RedshiftEventTopicSubscription:
    Type: 'AWS::SNS::Subscription'
    Properties:
      Protocol: 'email'
      Endpoint: !Ref EmailAddress
      TopicArn: !Ref RedshiftEventTopic

  # Create Redshift Event Subscription
  RedshiftEventSubscription:
    Type: 'AWS::Redshift::EventSubscription'
    Properties:
      SubscriptionName: !Ref EventSubscriptionName
      SnsTopicArn: !Ref RedshiftEventTopic
      SourceType: 'cluster'
      SourceIds: !If 
        - IsSpecificCluster
        - [!Ref ClusterIdentifier]
        - !Ref 'AWS::NoValue'
        #- !Ref ClusterIdentifier
      Severity: !Ref SeverityLevel
      Enabled: true
      EventCategories:
        - 'configuration'
        - 'management'
        - 'monitoring'
        - 'security'
        - 'pending'

Outputs:
  SNSTopicARN:
    Description: 'ARN of the created SNS Topic'
    Value: !Ref RedshiftEventTopic
  
  EventSubscriptionName:
    Description: 'Name of the created Event Subscription'
    Value: !Ref RedshiftEventSubscription
  
  MonitoringScope:
    Description: 'Showing if monitoring all clusters or specific cluster'
    Value: !If 
      - IsSpecificCluster
      - !Sub 'Monitoring specific cluster: ${ClusterIdentifier}'
      - 'Monitoring all clusters'

  SeverityMonitoring:
    Description: 'Showing severity level being monitored'
    Value: !Sub 'Monitoring ${SeverityLevel} severity'
