AWSTemplateFormatVersion: 2010-09-09
Description: Dynatrace Data Acquisition AWS monitoring integration - metrics and smartscape (v0.8.3)

Metadata:
  Version:
    Number: v0.8.3

Parameters:
  DynatraceUrl:
    Type: String
    AllowedPattern: "^https:\\/\\/.+[^\\/]$"
  MonitoringConfigurationId:
    Description: AWS monitoring extension configuration ID
    Type: String
  DynatraceApiClientFunctionArn:
    Description: ARN of Dynatrace API client Lambda function
    Type: String
    MinLength: 1
  DynatraceApiTokenSecretArn:
    Description: ARN of secret with Dynatrace settings token
    Type: String
    MinLength: 1

Resources:
  HasConfigurationResource:
    Type: "Custom::DynatraceApiAccessFunction"
    Properties:
      ServiceToken: !Ref DynatraceApiClientFunctionArn
      ServiceTimeout: 120
      Step: HAS_CONFIGURATION
      DtApiKeySecret: !Ref DynatraceApiTokenSecretArn

  MonitoringRoleStack:
    Type: AWS::CloudFormation::Stack
    Properties:
      TemplateURL: https://dynatrace-data-acquisition.s3.amazonaws.com/aws/deployment/cfn/v0.8.3/da-aws-nested-monitoring-role.yaml
      Parameters:
        DynatraceUrl: !Ref DynatraceUrl
        RoleExternalId: !GetAtt HasConfigurationResource.SettingsObjectId
      Tags:
        - Key: 'CreatedBy'
          Value: 'Dynatrace'
        - Key: 'EnvironmentID'
          Value: !Select [ 0, !Split [ ".", !Select [ 1, !Split [ "https://", !Ref DynatraceUrl ] ] ] ]

  UpdatedHasResource:
    DependsOn: MonitoringRoleStack
    Type: "Custom::DynatraceApiAccessFunction"
    Properties:
      ServiceToken: !Ref DynatraceApiClientFunctionArn
      ServiceTimeout: 120
      Step: HAS_MONITORING_ROLE
      DtApiKeySecret: !Ref DynatraceApiTokenSecretArn
      SettingsObjectId: !GetAtt HasConfigurationResource.SettingsObjectId
      HASConnectionName: !GetAtt HasConfigurationResource.HASConnectionName
      MonitoringRole:
        !GetAtt
          - MonitoringRoleStack
          - Outputs.MonitoringRoleArn

  MonitoringConfigurationResource:
    DependsOn: UpdatedHasResource
    Type: "Custom::DynatraceApiAccessFunction"
    Properties:
      ServiceToken: !Ref DynatraceApiClientFunctionArn
      ServiceTimeout: 120
      Step: MONITORING_CONFIGURATION
      DtApiKeySecret: !Ref DynatraceApiTokenSecretArn
      MonitoringConfigurationId: !Ref MonitoringConfigurationId
      SettingsObjectId: !GetAtt HasConfigurationResource.SettingsObjectId
      HASConnectionName: !GetAtt HasConfigurationResource.HASConnectionName

Outputs:
  MonitoringConfigUuid:
    Value: !GetAtt MonitoringConfigurationResource.MonitoringConfigurationId
  HasSettingsObjectId:
    Value: !GetAtt HasConfigurationResource.SettingsObjectId
