Parameters:
  TargetJobName:
    Type: String
    Description: 'AWS Glue DataBrew Job name to be triggered after the event has occurred'
    MaxLength: 240
    MinLength: 1
    AllowedPattern: '^[a-zA-Z0-9-. ]+$'
  SourceJobName:
    Type: String
    Description: 'AWS Glue DataBrew Job name, for the event to be matched. Must be different from the TargetJobName'
    MaxLength: 240
    MinLength: 1
    AllowedPattern: '^[a-zA-Z0-9-. ]+$'
  IAMRoleOptionToTriggerDataBrewJob:
    AllowedValues: ['Create a new IAM Role', 'Attach an existing IAM Role']
    Description: 'IAM role arn consumed by AWS StepFunctions to trigger DataBrew target job'
    Default: 'Create a new IAM Role'
    Type: String
  RoleArnToTriggerDataBrewJob:
    Type: String
    Description: "Attach existing IAM role arn which will be consumed by AWS StepFunctions to trigger DataBrew target job. If 'Create a new IAMRole' option is chosen, this field will be ignored"
    AllowedPattern: '^(arn:aws:iam::\d{12}:role\/([0-9a-zA-Z_+=,.@-]+))*$'
  IAMRoleOptionToTriggerStateMachine:
    AllowedValues: ['Create a new IAM Role', 'Attach an existing IAM Role']
    Description: 'IAM role arn consumed by AWS EventBridge to trigger State machine'
    Default: 'Create a new IAM Role'
    Type: String
  RoleArnToTriggerStateMachine:
    Type: String
    Description: "Attach existing IAM role arn which will be consumed by AWS EventBridge to trigger State machine. If 'Create a new IAMRole' option is chosen, this field will be ignored"
    AllowedPattern: '^(arn:aws:iam::\d{12}:role\/([0-9a-zA-Z_+=,.@-]+))*$'

Metadata: 
  AWS::CloudFormation::Interface: 
    ParameterGroups: 
      - 
        Label: 
          default: "AWS Glue DataBrew Jobs"
        Parameters: 
          - SourceJobName
          - TargetJobName
      - 
        Label: 
          default: "AWS StepFunctions state machine IAM role configuration"
        Parameters: 
          - IAMRoleOptionToTriggerDataBrewJob
          - RoleArnToTriggerDataBrewJob
      - 
        Label: 
          default: "AWS EventBridge rule IAM role configuration"
        Parameters: 
          - IAMRoleOptionToTriggerStateMachine
          - RoleArnToTriggerStateMachine


    ParameterLabels: 
      TargetJobName: 
        default: "DataBrew target Job name"
      SourceJobName: 
        default: "DataBrew source Job name"
      IAMRoleOptionToTriggerDataBrewJob:
        default: "IAM role option"
      IAMRoleOptionToTriggerStateMachine:
        default: "IAM role option"
      RoleArnToTriggerDataBrewJob:
        default: "Enter an IAM role arn to trigger DataBrew job"
      RoleArnToTriggerStateMachine:
        default: "Enter an IAM role arn to trigger State machine"

Conditions:
  CreateANewIAMRoleForDataBrewJobs:
    !Not [!Equals [!Ref IAMRoleOptionToTriggerDataBrewJob, 'Attach an existing IAM Role']]
  CreateANewIAMRoleForStateMachine:
    !Not [!Equals [!Ref IAMRoleOptionToTriggerStateMachine, 'Attach an existing IAM Role']]


Rules:
  IAMRoleRuleForDataBrewJob:
    RuleCondition: !Equals [!Ref IAMRoleOptionToTriggerDataBrewJob, 'Attach an existing IAM Role']
    Assertions:
      - Assert: !Not [!Equals [!Ref RoleArnToTriggerDataBrewJob, '']]
        AssertDescription: "IAM Role arn field for DataBrew job cannot be empty if 'Attach an existing IAM Role' option is chosen"
  IAMRoleRuleForStateMachine:
    RuleCondition: !Equals [!Ref IAMRoleOptionToTriggerStateMachine, 'Attach an existing IAM Role']
    Assertions:
      - Assert: !Not [!Equals [!Ref RoleArnToTriggerStateMachine, '']]
        AssertDescription: "IAM Role arn field for state machine cannot be empty if 'Attach an existing IAM Role' option is chosen"

Resources:
  DeadLetterConfigQueue:
    Type: AWS::SQS::Queue
    Properties:
      QueueName: !Join ['', [!Ref 'AWS::StackName','_DeadLetterConfigQueue']]

  IAMRoleToTriggerDataBrewJob:
    Condition: CreateANewIAMRoleForDataBrewJobs
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - states.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Path: /
      Policies:
        - PolicyName: !Join ['', ['IAMRoleToTriggerDataBrewJob','_',!Ref 'AWS::StackName','_PolicyDocument']]
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action: ['databrew:startJobRun']
                Resource: [!Join ['', ['arn:', !Ref 'AWS::Partition', ':databrew:', !Ref 'AWS::Region', ':', !Ref 'AWS::AccountId', ':job/', !Ref 'TargetJobName']]]

  IAMRoleToTriggerStateMachine:
    Condition: CreateANewIAMRoleForStateMachine
    Type: 'AWS::IAM::Role'
    Properties:
      AssumeRolePolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: Allow
            Principal:
              Service:
                - events.amazonaws.com
            Action:
              - 'sts:AssumeRole'
      Path: /
      Policies:
        - PolicyName: !Join ['', ['IAMRoleToTriggerStateMachine','_',!Ref 'AWS::StackName','_PolicyDocument']]
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action: ['states:StartExecution']
                Resource: [!Join ['', ['arn:', !Ref 'AWS::Partition', ':states:', !Ref 'AWS::Region', ':', !Ref 'AWS::AccountId', ':stateMachine:', !Join ['', [!Ref 'AWS::StackName','_StateMachine']]]]]

  DeadLetterConfigQueuePolicy:
    DependsOn: DeadLetterConfigQueue
    Type: AWS::SQS::QueuePolicy
    Properties: 
      Queues: 
        - !Ref DeadLetterConfigQueue
      PolicyDocument: 
        Statement: 
          - 
            Action: 
              - 'SQS:SendMessage'
            Effect: 'Allow'
            Resource: !GetAtt [DeadLetterConfigQueue, Arn]
            Principal:  
              Service: 
                - events.amazonaws.com
            Condition:
              ArnEquals:
                'aws:SourceArn': !Join ['', ['arn:', !Ref 'AWS::Partition', ':events:', !Ref 'AWS::Region', ':', !Ref 'AWS::AccountId', ':rule/', !Join ['', [!Ref 'AWS::StackName','_Rule']]]]
    

  StateMachine:
    Type: AWS::StepFunctions::StateMachine
    Properties:
      StateMachineName: !Join ['', [!Ref 'AWS::StackName','_StateMachine']]
      DefinitionSubstitutions:
        TargetJobName: !Ref TargetJobName
      DefinitionString: |-
        {
          "StartAt": "Glue DataBrew StartJobRun",
          "States": {
            "Glue DataBrew StartJobRun": {
              "Type": "Task",
              "Resource": "arn:aws:states:::databrew:startJobRun",
              "Parameters": {
                "Name": "${TargetJobName}"
              },
              "End": true
            }
          }
        }
      RoleArn: !If [CreateANewIAMRoleForDataBrewJobs, !Join ['', ['arn:', !Ref 'AWS::Partition', ':iam::', !Ref 'AWS::AccountId', ':role/', !Ref 'IAMRoleToTriggerDataBrewJob']], !Ref RoleArnToTriggerDataBrewJob]

  EventsRuleWithDeadLetterConfig:
    Type: AWS::Events::Rule
    DependsOn: StateMachine
    Properties:
      Description: !Join ['', ['AWS Events Rule to match when AWS Glue DataBrew job ', !Ref 'SourceJobName', ' completes successfully and triggers AWS StepFunctions state machine ', !Join ['', [!Ref 'AWS::StackName','_StateMachine']], ', which in turn triggers AWS Glue DataBrew Job ', !Ref 'TargetJobName']]
      Name: !Join ['', [!Ref 'AWS::StackName','_Rule']]
      EventPattern: 
            source:
              - aws.databrew
            detail-type:
              - DataBrew Job State Change
            detail:
              jobName: 
                - !Ref SourceJobName
              state:
                - SUCCEEDED
      Targets: 
          - Arn: !Join ['', ['arn:', !Ref 'AWS::Partition', ':states:', !Ref 'AWS::Region', ':', !Ref 'AWS::AccountId', ':stateMachine:', !Join ['', [!Ref 'AWS::StackName','_StateMachine']]]]
            RoleArn: !If [CreateANewIAMRoleForStateMachine, !Join ['', ['arn:', !Ref 'AWS::Partition', ':iam::', !Ref 'AWS::AccountId', ':role/', !Ref 'IAMRoleToTriggerStateMachine']], !Ref RoleArnToTriggerStateMachine]
            Id: !Join ['', [!Ref 'AWS::StackName','_StateMachine']]
            DeadLetterConfig:
              Arn: !GetAtt [DeadLetterConfigQueue, Arn]




