AWSTemplateFormatVersion: "2010-09-09"
Description: >
  Cloud Cost Clinic resource-birth monitor. This stack creates a customer-owned
  EventBridge rule that forwards selected CloudTrail resource-creation events to
  the Cloud Cost Clinic event bus for proactive cost-risk alerts. It does not
  grant delete, stop, start, resize, secrets, or remediation permissions.

Parameters:
  ScannerEventBusArn:
    Type: String
    Description: Cloud Cost Clinic EventBridge event bus ARN for resource-birth alerts.
    AllowedPattern: "^arn:(aws|aws-us-gov|aws-cn):events:[a-z0-9-]+:[0-9]{12}:event-bus/[A-Za-z0-9._/-]+$"
    ConstraintDescription: Enter the EventBridge event bus ARN provided by Cloud Cost Clinic.

  MonitorName:
    Type: String
    Default: CloudCostClinicResourceBirthMonitor
    Description: Name for the EventBridge rule and forwarding role.
    MinLength: 1
    MaxLength: 48
    AllowedPattern: "^[A-Za-z0-9+=,.@_-]+$"

Resources:
  CloudCostClinicResourceBirthForwardRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub "${MonitorName}ForwardRole"
      Description: Allows the Cloud Cost Clinic resource-birth monitor rule to forward selected events.
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service: events.amazonaws.com
            Action: sts:AssumeRole
      Policies:
        - PolicyName: CloudCostClinicResourceBirthForwardPolicy
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Sid: PutEventsToCloudCostClinicBus
                Effect: Allow
                Action: events:PutEvents
                Resource: !Ref ScannerEventBusArn

  # EventBridge limits each rule's event pattern to 2048 characters, so the
  # watch list is split across two rules that share the same forwarding role
  # and target. Rule 1 covers creation events that need no parameter filters;
  # rule 2 covers the EC2 events that are filtered by instance type or volume
  # size/IOPS so routine small launches are never forwarded.
  CloudCostClinicResourceBirthRule:
    Type: AWS::Events::Rule
    Properties:
      Name: !Ref MonitorName
      Description: Forwards selected expensive-resource creation events to Cloud Cost Clinic; no remediation actions.
      State: ENABLED
      EventPattern:
        detail-type:
          - AWS API Call via CloudTrail
        source:
          - aws.ec2
          - aws.rds
          - aws.redshift
          - aws.es
          - aws.opensearch
          - aws.sagemaker
          - aws.eks
          - aws.elasticmapreduce
          - aws.kafka
          - aws.elasticache
          - aws.globalaccelerator
          - aws.kinesis
        detail:
          eventName:
            - CreateNatGateway
            - AllocateAddress
            - CreateTransitGateway
            - CreateTransitGatewayVpcAttachment
            - CreateTransitGatewayPeeringAttachment
            - CreateTransitGatewayConnect
            - CreateTransitGatewayConnectPeer
            - CreateVpnConnection
            - CreateFleet
            - RequestSpotFleet
            - CreateDBInstance
            - CreateDBCluster
            - CreateCluster
            - CreateClusterV2
            - CreateElasticsearchDomain
            - CreateDomain
            - CreateEndpoint
            - CreateNotebookInstance
            - CreateNodegroup
            - RunJobFlow
            - CreateCacheCluster
            - CreateReplicationGroup
            - CreateAccelerator
            - CreateStream
      Targets:
        - Arn: !Ref ScannerEventBusArn
          Id: CloudCostClinicResourceBirthEventBus
          RoleArn: !GetAtt CloudCostClinicResourceBirthForwardRole.Arn

  # CloudTrail serializes EC2 numeric request parameters (size, iops) as JSON
  # strings, and EventBridge numeric matching only works on JSON numbers - a
  # size/iops filter here can never match a real event. CreateVolume is
  # therefore forwarded unfiltered and the ingest Lambda's size/IOPS/type
  # filter decides whether an alert is created; small volumes are dropped
  # immediately and never stored. Instance types are strings, so the
  # RunInstances prefix/suffix filters below do work client-side.
  CloudCostClinicResourceBirthEc2Rule:
    Type: AWS::Events::Rule
    Properties:
      Name: !Sub "${MonitorName}Ec2"
      Description: Forwards expensive EC2 launches and volume creations to Cloud Cost Clinic (alerts only for large or high-IOPS volumes); no remediation actions.
      State: ENABLED
      EventPattern:
        detail-type:
          - AWS API Call via CloudTrail
        source:
          - aws.ec2
        $or:
          - detail:
              eventName:
                - RunInstances
              requestParameters:
                instanceType:
                  - prefix: p
                  - prefix: g
                  - prefix: trn
                  - prefix: inf
                  - prefix: x
                  - suffix: ".metal"
                  - suffix: ".xlarge"
                  - suffix: ".2xlarge"
                  - suffix: ".3xlarge"
                  - suffix: ".4xlarge"
                  - suffix: ".6xlarge"
                  - suffix: ".8xlarge"
                  - suffix: ".9xlarge"
                  - suffix: ".10xlarge"
                  - suffix: ".12xlarge"
                  - suffix: ".16xlarge"
                  - suffix: ".18xlarge"
                  - suffix: ".24xlarge"
                  - suffix: ".32xlarge"
                  - suffix: ".48xlarge"
                  - suffix: ".56xlarge"
                  - suffix: ".112xlarge"
          - detail:
              eventName:
                - CreateVolume
      Targets:
        - Arn: !Ref ScannerEventBusArn
          Id: CloudCostClinicResourceBirthEventBus
          RoleArn: !GetAtt CloudCostClinicResourceBirthForwardRole.Arn

Outputs:
  MonitorRuleName:
    Description: EventBridge rule that forwards resource-birth events.
    Value: !Ref CloudCostClinicResourceBirthRule

  MonitorEc2RuleName:
    Description: EventBridge rule that forwards filtered EC2 launch/volume events.
    Value: !Ref CloudCostClinicResourceBirthEc2Rule

  ForwardRoleArn:
    Description: Role used by EventBridge to forward selected events.
    Value: !GetAtt CloudCostClinicResourceBirthForwardRole.Arn
