AWSTemplateFormatVersion: '2010-09-09'
Description: Deploy Resources for enabling Tag Propagation for Aurora Serverless Resources
Resources:
  auroraTagPropagatorRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: auroraTagPropagatorRole
      Description: This role gives permission to Lambda function for reading DB Clusters & VPC endpoints, creating tags and log groups resources
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - lambda.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Policies:
        - PolicyName: auroraTaggingPolicy
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Sid: PermissionToCreateTags
              - Effect: Allow
                Resource: 
                  - "arn:aws:ec2:::vpc/*"
                  - "arn:aws:ec2:*:::vpc-endpoint/*"
                Action:
                  - "ec2:CreateTags"
              - Sid: PermissionToCreateLogsAndLogGroups
              - Effect: Allow
                Resource: '*'
                Action:
                  - "rds:DescribeDBClusters"
                  - "ec2:DescribeVpcEndpoints"
                  - "logs:CreateLogGroup"
                  - "logs:CreateLogStream"
                  - "logs:PutLogEvents"
      Tags:
        - Key: Name
          Value: auroraTagPropagatorRole

  taggingAuroraResources:
    Type: AWS::Lambda::Function
    FunctionName: auroraTagPropagator
    Description: This Lambda function's scope is to propagate tags to resources Aurora Serverless creates like VPC endpoints and Security Groups
    Properties:
      Handler: tagpropagator.lambda_handler
      Role: !GetAtt auroraTagPropagatorRole.Arn
      Code:
        S3Bucket: tagpropagator
        S3Key: tagPropagatorforAurora.zip
      Runtime: python3.8
      Timeout: 90
      TracingConfig:
        Mode: Active
      Tags: 
        - Key: Name
          Value: auroraTagPropagator

  propagateAuroraTagsRule:
    Type: AWS::Events::Rule
    Properties:
      Description: Invoke Lambda for tagging Aurora Resources
      Name: tagPropagatorForAurora
      EventPattern:
        source:
          - aws.rds
        detail-type:
          - AWS API Call via CloudTrail
        detail:
          eventSource:
            - rds.amazonaws.com
          eventName:
            - CreateDBCluster
      State: ENABLED
      Targets:
        - Arn: !GetAtt taggingAuroraResources.Arn
          Id: LambdaFucntion

  PermissionForEventsToInvokeLambda: 
    Type: AWS::Lambda::Permission
    Properties: 
      FunctionName: !Ref taggingAuroraResources
      Action: "lambda:InvokeFunction"
      Principal: "events.amazonaws.com"
      SourceArn: !GetAtt propagateAuroraTagsRule.Arn