AWSTemplateFormatVersion: "2010-09-09"
Description: Dynatrace Data Acquisition - AWS events ingest (v0.8.3)

Metadata:
  Version:
    Number: v0.8.3

Parameters:
  DtEnvironmentId:
    Description: Dynatrace environment ID
    Type: String
  DtIngestToken:
    Description: Secret with Dynatrace platform token for events ingest
    Type: String
  DacUrl:
    Description: Data Acquisition Controller URL
    Type: String
  EventBridgeBusName:
    Type: String
    Description: Name of the Amazon EventBridge bus from which to consume the events from.
    Default: default
    MinLength: 1
    MaxLength: 256
    AllowedPattern: "^[a-zA-Z0-9._-]*$"
  EventSources:
    Type: CommaDelimitedList
    Description: Comma-separated list of values of event sources to forward to Dynatrace (e.g. aws.health)
    Default: aws.health

Conditions:
  CustomEventBus: !Not [ !Equals [ 'default', !Ref EventBridgeBusName ]]

Resources:
  DynatraceEventBusConnection:
    Type: AWS::Events::Connection
    Properties:
      AuthorizationType: API_KEY
      AuthParameters:
        ApiKeyAuthParameters:
          ApiKeyName: Authorization
          ApiKeyValue: !Sub 'Bearer ${DtIngestToken}'
        InvocationHttpParameters:
          HeaderParameters:
            - Key: Dt-Tenant
              Value: !Ref DtEnvironmentId

  DynatraceApiDestination:
    Type: AWS::Events::ApiDestination
    Properties:
      ConnectionArn: !GetAtt DynatraceEventBusConnection.Arn
      HttpMethod: POST
      InvocationEndpoint: !Join
        - ""
        - - "https://"
          - !Ref DtEnvironmentId
          - "."
          - !Ref DacUrl
          - "/api/aws/eventbridge/v1/events"
      InvocationRateLimitPerSecond: 100

  EventBridgeToDynatraceIAMRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: events.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: AllowInvokeHttpApi
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action:
                  - events:InvokeApiDestination
                Resource: !Sub ${DynatraceApiDestination.Arn}

  DynatraceEventBridgeRule:
    Type: AWS::Events::Rule
    Properties:
      EventBusName: !If [ CustomEventBus, !Ref EventBridgeBusName, !Ref AWS::NoValue ]
      EventPattern:
        source: !Ref EventSources
      Targets:
        - Arn: !GetAtt DynatraceApiDestination.Arn
          RoleArn: !GetAtt EventBridgeToDynatraceIAMRole.Arn
          Id: dynatrace
          RetryPolicy:
            MaximumRetryAttempts: 185
            MaximumEventAgeInSeconds: 86400

Outputs:
  DynatraceEventsIngestTokenSecret:
    Value: !GetAtt DynatraceEventBusConnection.SecretArn
    Description: ARN of SecretsManager secret storing Dynatrace events ingest platform token
