Resources:
  Vpc8378EB38:
    Type: AWS::EC2::VPC
    Properties:
      CidrBlock: 10.0.0.0/16
      EnableDnsHostnames: true
      EnableDnsSupport: true
      InstanceTenancy: default
      Tags:
        - Key: Name
          Value: Beers/Vpc
    Metadata:
      aws:cdk:path: Beers/Vpc/Resource
  VpcSubnetSubnet1Subnet4E2E7556:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId:
        Ref: Vpc8378EB38
      AvailabilityZone:
        Fn::Select:
          - 0
          - Fn::GetAZs: ""
      CidrBlock: 10.0.0.0/17
      MapPublicIpOnLaunch: true
      Tags:
        - Key: aws-cdk:subnet-name
          Value: Subnet
        - Key: aws-cdk:subnet-type
          Value: Public
        - Key: Name
          Value: Beers/Vpc/SubnetSubnet1
    Metadata:
      aws:cdk:path: Beers/Vpc/SubnetSubnet1/Subnet
  VpcSubnetSubnet1RouteTableE98F7460:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId:
        Ref: Vpc8378EB38
      Tags:
        - Key: Name
          Value: Beers/Vpc/SubnetSubnet1
    Metadata:
      aws:cdk:path: Beers/Vpc/SubnetSubnet1/RouteTable
  VpcSubnetSubnet1RouteTableAssociationAE38B070:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId:
        Ref: VpcSubnetSubnet1RouteTableE98F7460
      SubnetId:
        Ref: VpcSubnetSubnet1Subnet4E2E7556
    Metadata:
      aws:cdk:path: Beers/Vpc/SubnetSubnet1/RouteTableAssociation
  VpcSubnetSubnet1DefaultRouteA38203A9:
    Type: AWS::EC2::Route
    Properties:
      RouteTableId:
        Ref: VpcSubnetSubnet1RouteTableE98F7460
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId:
        Ref: VpcIGWD7BA715C
    DependsOn:
      - VpcVPCGWBF912B6E
    Metadata:
      aws:cdk:path: Beers/Vpc/SubnetSubnet1/DefaultRoute
  VpcSubnetSubnet2Subnet525F53A7:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId:
        Ref: Vpc8378EB38
      AvailabilityZone:
        Fn::Select:
          - 1
          - Fn::GetAZs: ""
      CidrBlock: 10.0.128.0/17
      MapPublicIpOnLaunch: true
      Tags:
        - Key: aws-cdk:subnet-name
          Value: Subnet
        - Key: aws-cdk:subnet-type
          Value: Public
        - Key: Name
          Value: Beers/Vpc/SubnetSubnet2
    Metadata:
      aws:cdk:path: Beers/Vpc/SubnetSubnet2/Subnet
  VpcSubnetSubnet2RouteTable9B756194:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId:
        Ref: Vpc8378EB38
      Tags:
        - Key: Name
          Value: Beers/Vpc/SubnetSubnet2
    Metadata:
      aws:cdk:path: Beers/Vpc/SubnetSubnet2/RouteTable
  VpcSubnetSubnet2RouteTableAssociationEE1EED76:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      RouteTableId:
        Ref: VpcSubnetSubnet2RouteTable9B756194
      SubnetId:
        Ref: VpcSubnetSubnet2Subnet525F53A7
    Metadata:
      aws:cdk:path: Beers/Vpc/SubnetSubnet2/RouteTableAssociation
  VpcSubnetSubnet2DefaultRoute7E12473B:
    Type: AWS::EC2::Route
    Properties:
      RouteTableId:
        Ref: VpcSubnetSubnet2RouteTable9B756194
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId:
        Ref: VpcIGWD7BA715C
    DependsOn:
      - VpcVPCGWBF912B6E
    Metadata:
      aws:cdk:path: Beers/Vpc/SubnetSubnet2/DefaultRoute
  VpcIGWD7BA715C:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: Beers/Vpc
    Metadata:
      aws:cdk:path: Beers/Vpc/IGW
  VpcVPCGWBF912B6E:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId:
        Ref: Vpc8378EB38
      InternetGatewayId:
        Ref: VpcIGWD7BA715C
    Metadata:
      aws:cdk:path: Beers/Vpc/VPCGW
  VpcS3A5408339:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      ServiceName:
        Fn::Join:
          - ""
          - - com.amazonaws.
            - Ref: AWS::Region
            - .s3
      VpcId:
        Ref: Vpc8378EB38
      RouteTableIds:
        - Ref: VpcSubnetSubnet1RouteTableE98F7460
        - Ref: VpcSubnetSubnet2RouteTable9B756194
      VpcEndpointType: Gateway
    Metadata:
      aws:cdk:path: Beers/Vpc/S3/Resource
  LaunchTemplate04EC5460:
    Type: AWS::EC2::LaunchTemplate
    Properties:
      LaunchTemplateData:
        BlockDeviceMappings:
          - DeviceName: /dev/xvda
            Ebs:
              Iops: 16000
              Throughput: 1000
              VolumeSize: 1024
              VolumeType: gp3
        TagSpecifications:
          - ResourceType: instance
            Tags:
              - Key: Name
                Value: Beers/LaunchTemplate
          - ResourceType: volume
            Tags:
              - Key: Name
                Value: Beers/LaunchTemplate
      TagSpecifications:
        - ResourceType: launch-template
          Tags:
            - Key: Name
              Value: Beers/LaunchTemplate
    Metadata:
      aws:cdk:path: Beers/LaunchTemplate/Resource
  ComputeEnvironmentResourceSecurityGroup3E96E6FC:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Beers/ComputeEnvironment/Resource-Security-Group
      SecurityGroupEgress:
        - CidrIp: 0.0.0.0/0
          Description: Allow all outbound traffic by default
          IpProtocol: "-1"
      VpcId:
        Ref: Vpc8378EB38
    DependsOn:
      - VpcIGWD7BA715C
      - Vpc8378EB38
      - VpcS3A5408339
      - VpcSubnetSubnet1DefaultRouteA38203A9
      - VpcSubnetSubnet1RouteTableE98F7460
      - VpcSubnetSubnet1RouteTableAssociationAE38B070
      - VpcSubnetSubnet1Subnet4E2E7556
      - VpcSubnetSubnet2DefaultRoute7E12473B
      - VpcSubnetSubnet2RouteTable9B756194
      - VpcSubnetSubnet2RouteTableAssociationEE1EED76
      - VpcSubnetSubnet2Subnet525F53A7
      - VpcVPCGWBF912B6E
    Metadata:
      aws:cdk:path: Beers/ComputeEnvironment/Resource-Security-Group/Resource
  ComputeEnvironmentEcsInstanceRoleFE696BC2:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: ec2.amazonaws.com
        Version: "2012-10-17"
      ManagedPolicyArns:
        - Fn::Join:
            - ""
            - - "arn:"
              - Ref: AWS::Partition
              - :iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role
    DependsOn:
      - VpcIGWD7BA715C
      - Vpc8378EB38
      - VpcS3A5408339
      - VpcSubnetSubnet1DefaultRouteA38203A9
      - VpcSubnetSubnet1RouteTableE98F7460
      - VpcSubnetSubnet1RouteTableAssociationAE38B070
      - VpcSubnetSubnet1Subnet4E2E7556
      - VpcSubnetSubnet2DefaultRoute7E12473B
      - VpcSubnetSubnet2RouteTable9B756194
      - VpcSubnetSubnet2RouteTableAssociationEE1EED76
      - VpcSubnetSubnet2Subnet525F53A7
      - VpcVPCGWBF912B6E
    Metadata:
      aws:cdk:path: Beers/ComputeEnvironment/Ecs-Instance-Role/Resource
  ComputeEnvironmentInstanceProfile42D17404:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Roles:
        - Ref: ComputeEnvironmentEcsInstanceRoleFE696BC2
    DependsOn:
      - VpcIGWD7BA715C
      - Vpc8378EB38
      - VpcS3A5408339
      - VpcSubnetSubnet1DefaultRouteA38203A9
      - VpcSubnetSubnet1RouteTableE98F7460
      - VpcSubnetSubnet1RouteTableAssociationAE38B070
      - VpcSubnetSubnet1Subnet4E2E7556
      - VpcSubnetSubnet2DefaultRoute7E12473B
      - VpcSubnetSubnet2RouteTable9B756194
      - VpcSubnetSubnet2RouteTableAssociationEE1EED76
      - VpcSubnetSubnet2Subnet525F53A7
      - VpcVPCGWBF912B6E
    Metadata:
      aws:cdk:path: Beers/ComputeEnvironment/Instance-Profile
  ComputeEnvironmentResourceServiceInstanceRoleDC6D4445:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: batch.amazonaws.com
        Version: "2012-10-17"
      ManagedPolicyArns:
        - Fn::Join:
            - ""
            - - "arn:"
              - Ref: AWS::Partition
              - :iam::aws:policy/service-role/AWSBatchServiceRole
    DependsOn:
      - VpcIGWD7BA715C
      - Vpc8378EB38
      - VpcS3A5408339
      - VpcSubnetSubnet1DefaultRouteA38203A9
      - VpcSubnetSubnet1RouteTableE98F7460
      - VpcSubnetSubnet1RouteTableAssociationAE38B070
      - VpcSubnetSubnet1Subnet4E2E7556
      - VpcSubnetSubnet2DefaultRoute7E12473B
      - VpcSubnetSubnet2RouteTable9B756194
      - VpcSubnetSubnet2RouteTableAssociationEE1EED76
      - VpcSubnetSubnet2Subnet525F53A7
      - VpcVPCGWBF912B6E
    Metadata:
      aws:cdk:path: Beers/ComputeEnvironment/Resource-Service-Instance-Role/Resource
  ComputeEnvironmentC570994D:
    Type: AWS::Batch::ComputeEnvironment
    Properties:
      Type: MANAGED
      ComputeResources:
        AllocationStrategy: BEST_FIT
        InstanceRole:
          Fn::GetAtt:
            - ComputeEnvironmentInstanceProfile42D17404
            - Arn
        InstanceTypes:
          - m6a.8xlarge
        LaunchTemplate:
          LaunchTemplateId:
            Ref: LaunchTemplate04EC5460
        MaxvCpus: 1568
        MinvCpus: 0
        SecurityGroupIds:
          - Fn::GetAtt:
              - ComputeEnvironmentResourceSecurityGroup3E96E6FC
              - GroupId
        Subnets:
          - Ref: VpcSubnetSubnet1Subnet4E2E7556
          - Ref: VpcSubnetSubnet2Subnet525F53A7
        Type: EC2
      ServiceRole:
        Fn::GetAtt:
          - ComputeEnvironmentResourceServiceInstanceRoleDC6D4445
          - Arn
      State: ENABLED
    DependsOn:
      - VpcIGWD7BA715C
      - Vpc8378EB38
      - VpcS3A5408339
      - VpcSubnetSubnet1DefaultRouteA38203A9
      - VpcSubnetSubnet1RouteTableE98F7460
      - VpcSubnetSubnet1RouteTableAssociationAE38B070
      - VpcSubnetSubnet1Subnet4E2E7556
      - VpcSubnetSubnet2DefaultRoute7E12473B
      - VpcSubnetSubnet2RouteTable9B756194
      - VpcSubnetSubnet2RouteTableAssociationEE1EED76
      - VpcSubnetSubnet2Subnet525F53A7
      - VpcVPCGWBF912B6E
    Metadata:
      aws:cdk:path: Beers/ComputeEnvironment/Resource
  JobQueueEE3AD499:
    Type: AWS::Batch::JobQueue
    Properties:
      ComputeEnvironmentOrder:
        - ComputeEnvironment:
            Ref: ComputeEnvironmentC570994D
          Order: 1
      Priority: 1
      State: ENABLED
    Metadata:
      aws:cdk:path: Beers/JobQueue/Resource
  ControlEnvironmentResourceSecurityGroup89F99A04:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Beers/ControlEnvironment/Resource-Security-Group
      SecurityGroupEgress:
        - CidrIp: 0.0.0.0/0
          Description: Allow all outbound traffic by default
          IpProtocol: "-1"
      VpcId:
        Ref: Vpc8378EB38
    DependsOn:
      - VpcIGWD7BA715C
      - Vpc8378EB38
      - VpcS3A5408339
      - VpcSubnetSubnet1DefaultRouteA38203A9
      - VpcSubnetSubnet1RouteTableE98F7460
      - VpcSubnetSubnet1RouteTableAssociationAE38B070
      - VpcSubnetSubnet1Subnet4E2E7556
      - VpcSubnetSubnet2DefaultRoute7E12473B
      - VpcSubnetSubnet2RouteTable9B756194
      - VpcSubnetSubnet2RouteTableAssociationEE1EED76
      - VpcSubnetSubnet2Subnet525F53A7
      - VpcVPCGWBF912B6E
    Metadata:
      aws:cdk:path: Beers/ControlEnvironment/Resource-Security-Group/Resource
  ControlEnvironmentEcsInstanceRole4D7BA33E:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: ec2.amazonaws.com
        Version: "2012-10-17"
      ManagedPolicyArns:
        - Fn::Join:
            - ""
            - - "arn:"
              - Ref: AWS::Partition
              - :iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role
    DependsOn:
      - VpcIGWD7BA715C
      - Vpc8378EB38
      - VpcS3A5408339
      - VpcSubnetSubnet1DefaultRouteA38203A9
      - VpcSubnetSubnet1RouteTableE98F7460
      - VpcSubnetSubnet1RouteTableAssociationAE38B070
      - VpcSubnetSubnet1Subnet4E2E7556
      - VpcSubnetSubnet2DefaultRoute7E12473B
      - VpcSubnetSubnet2RouteTable9B756194
      - VpcSubnetSubnet2RouteTableAssociationEE1EED76
      - VpcSubnetSubnet2Subnet525F53A7
      - VpcVPCGWBF912B6E
    Metadata:
      aws:cdk:path: Beers/ControlEnvironment/Ecs-Instance-Role/Resource
  ControlEnvironmentInstanceProfile8CECF8D8:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Roles:
        - Ref: ControlEnvironmentEcsInstanceRole4D7BA33E
    DependsOn:
      - VpcIGWD7BA715C
      - Vpc8378EB38
      - VpcS3A5408339
      - VpcSubnetSubnet1DefaultRouteA38203A9
      - VpcSubnetSubnet1RouteTableE98F7460
      - VpcSubnetSubnet1RouteTableAssociationAE38B070
      - VpcSubnetSubnet1Subnet4E2E7556
      - VpcSubnetSubnet2DefaultRoute7E12473B
      - VpcSubnetSubnet2RouteTable9B756194
      - VpcSubnetSubnet2RouteTableAssociationEE1EED76
      - VpcSubnetSubnet2Subnet525F53A7
      - VpcVPCGWBF912B6E
    Metadata:
      aws:cdk:path: Beers/ControlEnvironment/Instance-Profile
  ControlEnvironmentResourceServiceInstanceRole0568397F:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: batch.amazonaws.com
        Version: "2012-10-17"
      ManagedPolicyArns:
        - Fn::Join:
            - ""
            - - "arn:"
              - Ref: AWS::Partition
              - :iam::aws:policy/service-role/AWSBatchServiceRole
    DependsOn:
      - VpcIGWD7BA715C
      - Vpc8378EB38
      - VpcS3A5408339
      - VpcSubnetSubnet1DefaultRouteA38203A9
      - VpcSubnetSubnet1RouteTableE98F7460
      - VpcSubnetSubnet1RouteTableAssociationAE38B070
      - VpcSubnetSubnet1Subnet4E2E7556
      - VpcSubnetSubnet2DefaultRoute7E12473B
      - VpcSubnetSubnet2RouteTable9B756194
      - VpcSubnetSubnet2RouteTableAssociationEE1EED76
      - VpcSubnetSubnet2Subnet525F53A7
      - VpcVPCGWBF912B6E
    Metadata:
      aws:cdk:path: Beers/ControlEnvironment/Resource-Service-Instance-Role/Resource
  ControlEnvironment44FB94B2:
    Type: AWS::Batch::ComputeEnvironment
    Properties:
      Type: MANAGED
      ComputeResources:
        AllocationStrategy: BEST_FIT
        InstanceRole:
          Fn::GetAtt:
            - ControlEnvironmentInstanceProfile8CECF8D8
            - Arn
        InstanceTypes:
          - c6a.2xlarge
        LaunchTemplate:
          LaunchTemplateId:
            Ref: LaunchTemplate04EC5460
        MaxvCpus: 8
        MinvCpus: 0
        SecurityGroupIds:
          - Fn::GetAtt:
              - ControlEnvironmentResourceSecurityGroup89F99A04
              - GroupId
        Subnets:
          - Ref: VpcSubnetSubnet1Subnet4E2E7556
          - Ref: VpcSubnetSubnet2Subnet525F53A7
        Type: EC2
      ServiceRole:
        Fn::GetAtt:
          - ControlEnvironmentResourceServiceInstanceRole0568397F
          - Arn
      State: ENABLED
    DependsOn:
      - VpcIGWD7BA715C
      - Vpc8378EB38
      - VpcS3A5408339
      - VpcSubnetSubnet1DefaultRouteA38203A9
      - VpcSubnetSubnet1RouteTableE98F7460
      - VpcSubnetSubnet1RouteTableAssociationAE38B070
      - VpcSubnetSubnet1Subnet4E2E7556
      - VpcSubnetSubnet2DefaultRoute7E12473B
      - VpcSubnetSubnet2RouteTable9B756194
      - VpcSubnetSubnet2RouteTableAssociationEE1EED76
      - VpcSubnetSubnet2Subnet525F53A7
      - VpcVPCGWBF912B6E
    Metadata:
      aws:cdk:path: Beers/ControlEnvironment/Resource
  ControlQueue9204A4FA:
    Type: AWS::Batch::JobQueue
    Properties:
      ComputeEnvironmentOrder:
        - ComputeEnvironment:
            Ref: ControlEnvironment44FB94B2
          Order: 1
      Priority: 1
      State: ENABLED
    Metadata:
      aws:cdk:path: Beers/ControlQueue/Resource
  JobRole014917C6:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: ecs-tasks.amazonaws.com
        Version: "2012-10-17"
    Metadata:
      aws:cdk:path: Beers/JobRole/Resource
  JobRoleDefaultPolicy5DE0D8F9:
    Type: AWS::IAM::Policy
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - batch:DescribeJobs
              - batch:ListJobs
            Effect: Allow
            Resource: "*"
          - Action:
              - batch:SubmitJob
              - batch:TerminateJob
            Effect: Allow
            Resource:
              - Fn::Join:
                  - ""
                  - - "arn:"
                    - Ref: AWS::Partition
                    - ":batch:"
                    - Ref: AWS::Region
                    - ":"
                    - Ref: AWS::AccountId
                    - :job/*
              - Ref: JobDefinition24FFE3ED
              - Ref: JobQueueEE3AD499
          - Action:
              - s3:Abort*
              - s3:DeleteObject*
              - s3:GetBucket*
              - s3:GetObject*
              - s3:List*
              - s3:PutObject
              - s3:PutObjectLegalHold
              - s3:PutObjectRetention
              - s3:PutObjectTagging
              - s3:PutObjectVersionTagging
            Effect: Allow
            Resource:
              - Fn::Join:
                  - ""
                  - - "arn:"
                    - Ref: AWS::Partition
                    - ":s3:::"
                    - Ref: BucketName
                    - /*
              - Fn::Join:
                  - ""
                  - - "arn:"
                    - Ref: AWS::Partition
                    - ":s3:::"
                    - Ref: BucketName
          - Action:
              - states:SendTaskFailure
              - states:SendTaskHeartbeat
              - states:SendTaskSuccess
            Effect: Allow
            Resource:
              Ref: StateMachine2E01A3A5
        Version: "2012-10-17"
      PolicyName: JobRoleDefaultPolicy5DE0D8F9
      Roles:
        - Ref: JobRole014917C6
    Metadata:
      aws:cdk:path: Beers/JobRole/DefaultPolicy/Resource
  JobDefinition24FFE3ED:
    Type: AWS::Batch::JobDefinition
    Properties:
      Type: container
      ContainerProperties:
        Environment:
          - Name: AWS_DEFAULT_REGION
            Value:
              Ref: AWS::Region
          - Name: BUCKET_NAME
            Value:
              Ref: BucketName
          - Name: JOB_QUEUE_ARN
            Value:
              Ref: JobQueueEE3AD499
          - Name: PYTHONUNBUFFERED
            Value: "TRUE"
          - Name: STORAGE_TYPE
            Value: OBJECT
          - Name: AWS_REGION
            Value:
              Ref: AWS::Region
          - Name: AWS_ACCOUNT
            Value:
              Ref: AWS::AccountId
        Image: public.ecr.aws/s6z2x1b8/beers:0.1a
        JobRoleArn:
          Fn::GetAtt:
            - JobRole014917C6
            - Arn
        Privileged: false
        ReadonlyRootFilesystem: false
        ResourceRequirements:
          - Type: VCPU
            Value: "1"
          - Type: MEMORY
            Value: "4"
      PlatformCapabilities:
        - EC2
      RetryStrategy:
        Attempts: 1
      Timeout: {}
    Metadata:
      aws:cdk:path: Beers/JobDefinition/Resource
  StateMachineRoleB840431D:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: states.amazonaws.com
        Version: "2012-10-17"
    Metadata:
      aws:cdk:path: Beers/StateMachine/Role/Resource
  StateMachineRoleDefaultPolicyDF1E6607:
    Type: AWS::IAM::Policy
    Properties:
      PolicyDocument:
        Statement:
          - Action: batch:SubmitJob
            Effect: Allow
            Resource:
              - Fn::Join:
                  - ""
                  - - "arn:"
                    - Ref: AWS::Partition
                    - ":batch:"
                    - Ref: AWS::Region
                    - ":"
                    - Ref: AWS::AccountId
                    - :job-definition/*
              - Ref: ControlQueue9204A4FA
          - Action:
              - events:DescribeRule
              - events:PutRule
              - events:PutTargets
            Effect: Allow
            Resource:
              Fn::Join:
                - ""
                - - "arn:"
                  - Ref: AWS::Partition
                  - ":events:"
                  - Ref: AWS::Region
                  - ":"
                  - Ref: AWS::AccountId
                  - :rule/StepFunctionsGetEventsForBatchJobsRule
        Version: "2012-10-17"
      PolicyName: StateMachineRoleDefaultPolicyDF1E6607
      Roles:
        - Ref: StateMachineRoleB840431D
    Metadata:
      aws:cdk:path: Beers/StateMachine/Role/DefaultPolicy/Resource
  StateMachine2E01A3A5:
    Type: AWS::StepFunctions::StateMachine
    Properties:
      RoleArn:
        Fn::GetAtt:
          - StateMachineRoleB840431D
          - Arn
      DefinitionString:
        Fn::Join:
          - ""
          - - '{"StartAt":"ValidateConfiguration","States":{"ValidateConfiguration":{"Next":"ExecuteSimulation","Type":"Task","Resource":"arn:'
            - Ref: AWS::Partition
            - :states:::batch:submitJob.sync","Parameters":{"JobDefinition":"
            - Ref: JobDefinition24FFE3ED
            - '","JobName":"ValidateConfiguration","JobQueue":"'
            - Ref: ControlQueue9204A4FA
            - '","ContainerOverrides":{"Command":["execute.py"],"Environment":[{"Name":"EXECUTION_NAME","Value.$":"$$.Execution.Name"},{"Name":"TASK_TOKEN","Value.$":"$$.Task.Token"},{"Name":"JOB_DEFINITION_ARN","Value":"'
            - Ref: JobDefinition24FFE3ED
            - '"},{"Name":"INPUT","Value.$":"States.JsonToString($)"},{"Name":"STEP_NAME","Value":"ValidateConfiguration"}],"ResourceRequirements":[{"Type":"MEMORY","Value":"4096"},{"Type":"VCPU","Value":"2"}]}}},"ExecuteSimulation":{"Next":"ExecutionCompleted","Catch":[{"ErrorEquals":["States.ALL"],"Next":"AbortExecutionOnError"}],"Type":"Task","Resource":"arn:'
            - Ref: AWS::Partition
            - :states:::batch:submitJob.sync","Parameters":{"JobDefinition":"
            - Ref: JobDefinition24FFE3ED
            - '","JobName":"ExecuteSimulation","JobQueue":"'
            - Ref: ControlQueue9204A4FA
            - '","ContainerOverrides":{"Command":["execute.py"],"Environment":[{"Name":"EXECUTION_NAME","Value.$":"$$.Execution.Name"},{"Name":"TASK_TOKEN","Value.$":"$$.Task.Token"},{"Name":"JOB_DEFINITION_ARN","Value":"'
            - Ref: JobDefinition24FFE3ED
            - '"},{"Name":"INPUT","Value.$":"States.JsonToString($)"},{"Name":"STEP_NAME","Value":"ExecuteSimulation"}],"ResourceRequirements":[{"Type":"MEMORY","Value":"4096"},{"Type":"VCPU","Value":"2"}]}}},"ExecutionCompleted":{"Type":"Succeed"},"AbortExecutionOnError":{"Next":"ExecutionFailed","Type":"Task","Resource":"arn:'
            - Ref: AWS::Partition
            - :states:::batch:submitJob.sync","Parameters":{"JobDefinition":"
            - Ref: JobDefinition24FFE3ED
            - '","JobName":"AbortExecutionOnError","JobQueue":"'
            - Ref: ControlQueue9204A4FA
            - '","ContainerOverrides":{"Command":["execute.py"],"Environment":[{"Name":"EXECUTION_NAME","Value.$":"$$.Execution.Name"},{"Name":"TASK_TOKEN","Value.$":"$$.Task.Token"},{"Name":"JOB_DEFINITION_ARN","Value":"'
            - Ref: JobDefinition24FFE3ED
            - '"},{"Name":"INPUT","Value.$":"States.JsonToString($)"},{"Name":"STEP_NAME","Value":"AbortExecutionOnError"}],"ResourceRequirements":[{"Type":"MEMORY","Value":"4096"},{"Type":"VCPU","Value":"2"}]},"RetryStrategy":{"Attempts":3}}},"ExecutionFailed":{"Type":"Fail"}}}'
    DependsOn:
      - StateMachineRoleDefaultPolicyDF1E6607
      - StateMachineRoleB840431D
    UpdateReplacePolicy: Delete
    DeletionPolicy: Delete
    Metadata:
      aws:cdk:path: Beers/StateMachine/Resource
  InitializeFunctionServiceRole5E889CE7:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Statement:
          - Action: sts:AssumeRole
            Effect: Allow
            Principal:
              Service: lambda.amazonaws.com
        Version: "2012-10-17"
      ManagedPolicyArns:
        - Fn::Join:
            - ""
            - - "arn:"
              - Ref: AWS::Partition
              - :iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
    Metadata:
      aws:cdk:path: Beers/InitializeFunction/ServiceRole/Resource
  InitializeFunctionServiceRoleDefaultPolicy5BC6C3DA:
    Type: AWS::IAM::Policy
    Properties:
      PolicyDocument:
        Statement:
          - Action:
              - batch:DescribeComputeEnvironments
              - ecs:DescribeClusters
              - ecs:UpdateClusterSettings
            Effect: Allow
            Resource: "*"
          - Action:
              - s3:DeleteMetricsConfiguration
              - s3:PutMetricsConfiguration
            Effect: Allow
            Resource:
              Fn::Join:
                - ""
                - - "arn:"
                  - Ref: AWS::Partition
                  - ":s3:::"
                  - Ref: BucketName
          - Action: s3:PutObject
            Effect: Allow
            Resource:
              Fn::Join:
                - ""
                - - "arn:"
                  - Ref: AWS::Partition
                  - ":s3:::"
                  - Ref: BucketName
                  - /BeersInstructions.html
        Version: "2012-10-17"
      PolicyName: InitializeFunctionServiceRoleDefaultPolicy5BC6C3DA
      Roles:
        - Ref: InitializeFunctionServiceRole5E889CE7
    Metadata:
      aws:cdk:path: Beers/InitializeFunction/ServiceRole/DefaultPolicy/Resource
  InitializeFunction358A5BA5:
    Type: AWS::Lambda::Function
    Properties:
      Code:
        ZipFile: |
          import boto3
          import json
          import os
          import urllib3

          from botocore.exceptions import ClientError


          def send_response(
              event, context, status, data, physical_resource_id=None, no_echo=False
          ):
              assert status in {"SUCCESS", "FAILED"}

              response_url = event["ResponseURL"]

              response_body = {}
              response_body["Status"] = status
              response_body["Reason"] = (
                  "See the details in CloudWatch Log Stream: " + context.log_stream_name
              )
              response_body["PhysicalResourceId"] = (
                  physical_resource_id or context.log_stream_name
              )
              response_body["StackId"] = event["StackId"]
              response_body["RequestId"] = event["RequestId"]
              response_body["LogicalResourceId"] = event["LogicalResourceId"]
              response_body["NoEcho"] = no_echo
              response_body["Data"] = data

              json_response_body = json.dumps(response_body)
              headers = {"content-type": "", "content-length": str(len(json_response_body))}

              print("Headers:", headers)
              print("Response body:", json_response_body)

              http = urllib3.PoolManager()

              try:
                  http.request(
                      "PUT",
                      response_url,
                      body=json_response_body.encode("utf-8"),
                      headers=headers,
                      retries=urllib3.Retry(10, backoff_factor=0.5),
                  )
              except Exception as exception:
                  print("Exception:", exception)


          def handle(event, context):
              request_type = event["RequestType"]
              resource_properties = event["ResourceProperties"]

              stack_name = os.environ["STACK_NAME"]
              bucket_name = os.environ["BUCKET_NAME"]
              metrics_configuration_id = f"{stack_name}EntireBucket"

              batch = boto3.client("batch")
              ecs = boto3.client("ecs")
              s3 = boto3.client("s3")

              if request_type == "Create" or request_type == "Update":
                  compute_environment_arn = os.environ["COMPUTE_ENVIRONMENT_ARN"]

                  compute_environment, *_ = batch.describe_compute_environments(
                      computeEnvironments=[compute_environment_arn]
                  )["computeEnvironments"]

                  cluster_arn = compute_environment["ecsClusterArn"]

                  cluster, *_ = ecs.describe_clusters(clusters=[cluster_arn])["clusters"]
                  cluster_name = cluster["clusterName"]

                  if resource_properties["Action"] == "GetClusterName":
                      send_response(event, context, "SUCCESS", {"ClusterName": cluster_name})

                  elif resource_properties["Action"] == "Initialize":
                      if os.environ["ENABLE_DETAILED_MONITORING"] == "True":
                          ecs.update_cluster_settings(
                              cluster=cluster_arn,
                              settings=[{"name": "containerInsights", "value": "enabled"}],
                          )

                          s3.put_bucket_metrics_configuration(
                              Bucket=bucket_name,
                              Id=metrics_configuration_id,
                              MetricsConfiguration={"Id": metrics_configuration_id},
                          )

                      http = urllib3.PoolManager()
                      instructions = http.request(
                          "GET",
                          "http://bioinf.itmat.upenn.edu/BEERS2/stack/instructions/template.html",
                      ).data.decode()

                      variables = [
                          "AWS_REGION",
                          "BUCKET_NAME",
                          "COMPUTE_ENVIRONMENT_ARN",
                          "JOB_QUEUE_NAME",
                          "STATE_MACHINE_ARN",
                      ]

                      for variable in variables:
                          instructions = instructions.replace(
                              "{{" + variable + "}}", os.environ[variable]
                          )

                      s3.put_object(
                          Bucket=bucket_name,
                          Key=f"{stack_name}Instructions.html",
                          Body=instructions.encode(),
                      )

                      send_response(event, context, "SUCCESS", {})
                  else:
                      print("Invalid action:", resource_properties["Action"])
                      send_response(event, context, "FAILED", {})

              elif request_type == "Delete":
                  if os.environ["ENABLE_DETAILED_MONITORING"] == "True":
                      compute_environment_arn = os.environ["COMPUTE_ENVIRONMENT_ARN"]

                      compute_environment, *_ = batch.describe_compute_environments(
                          computeEnvironments=[compute_environment_arn]
                      )["computeEnvironments"]

                      cluster_arn = compute_environment["ecsClusterArn"]

                      ecs.update_cluster_settings(
                          cluster=cluster_arn,
                          settings=[{"name": "containerInsights", "value": "disabled"}],
                      )
                      
                      try:
                          s3.delete_bucket_metrics_configuration(
                              Bucket=bucket_name, Id=metrics_configuration_id
                          )
                      except ClientError as exception:
                          if exception.response["Error"]["Code"] != "NoSuchConfiguration":
                              raise exception

                  send_response(event, context, "SUCCESS", {})
              else:
                  print("Invalid request type:", request_type)
                  send_response(event, context, "FAILED", {})


          def on_event(event, context):
              print(event, context)
              try:
                  handle(event, context)
              except Exception as exception:
                  print("Exception:", exception)
                  send_response(event, context, "FAILED", {})
      Role:
        Fn::GetAtt:
          - InitializeFunctionServiceRole5E889CE7
          - Arn
      Environment:
        Variables:
          BUCKET_NAME:
            Ref: BucketName
          COMPUTE_ENVIRONMENT_ARN:
            Ref: ComputeEnvironmentC570994D
          JOB_QUEUE_NAME:
            Ref: JobQueueEE3AD499
          STACK_NAME: Beers
          STATE_MACHINE_ARN:
            Ref: StateMachine2E01A3A5
          ENABLE_DETAILED_MONITORING: "False"
      Handler: index.on_event
      MemorySize: 3008
      Runtime: python3.9
      Timeout: 900
    DependsOn:
      - InitializeFunctionServiceRoleDefaultPolicy5BC6C3DA
      - InitializeFunctionServiceRole5E889CE7
    Metadata:
      aws:cdk:path: Beers/InitializeFunction/Resource
  GetClusterName:
    Type: AWS::CloudFormation::CustomResource
    Properties:
      ServiceToken:
        Fn::GetAtt:
          - InitializeFunction358A5BA5
          - Arn
      Action: GetClusterName
    UpdateReplacePolicy: Delete
    DeletionPolicy: Delete
    Metadata:
      aws:cdk:path: Beers/GetClusterName/Default
  Initialize:
    Type: AWS::CloudFormation::CustomResource
    Properties:
      ServiceToken:
        Fn::GetAtt:
          - InitializeFunction358A5BA5
          - Arn
      Action: Initialize
    UpdateReplacePolicy: Delete
    DeletionPolicy: Delete
    Metadata:
      aws:cdk:path: Beers/Initialize/Default
  CDKMetadata:
    Type: AWS::CDK::Metadata
    Properties:
      Analytics: v2:deflate64:H4sIAAAAAAAA/21SwW7bMAz9ltwVNU0Ova7xuiJFB3hJ0WtBywysxqIMiVoRGP730Y6apMVOfHykKL4nLfXdQveLGXzEuakP89ZWut8xmIMS6q1Hs9T9a2dUsafXslBlqlprdqki5JG7oK1PjC9QtXjhL9x9jN5YYOvp3DyCDTEG6XwExg845mtyds+ySOOQWGVGNnmguvOWOLee02dIZJoXdF0Lp9nfmB2aFCwfH4NP3bTjNTGouNLrZA7Ia4ioLDjdb/1JzWfcUGQgg2XweytU6cWMaekTGlQFbBrdC1N414nIB/prg6dJhLBPvvqTMGHGP3FvyY6uDApN1IUnBksYLgUVGbu9KBmT+MYQD1Gvx2vEY2dZpnxt0f0vsK3aJWMQayWPyfhbfJSxk+qrfFAtuKoGOZJPjx2feBjUFqNPwUwHSwjgUJ5LFSmyd9e1aywa6ixpMYe2a0AvZj/yB7sZ42RSLvX/8els0leHBlUeufF0s9K3t3o5e4/WzkMitg719hT/AcDEFdrQAgAA
    Metadata:
      aws:cdk:path: Beers/CDKMetadata/Default
    Condition: CDKMetadataAvailable
Parameters:
  BucketName:
    Type: String
    Description: The name of your S3 bucket where input and output data will be stored.
Conditions:
  CDKMetadataAvailable:
    Fn::Or:
      - Fn::Or:
          - Fn::Equals:
              - Ref: AWS::Region
              - af-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-east-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-northeast-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-northeast-2
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-southeast-1
          - Fn::Equals:
              - Ref: AWS::Region
              - ap-southeast-2
          - Fn::Equals:
              - Ref: AWS::Region
              - ca-central-1
          - Fn::Equals:
              - Ref: AWS::Region
              - cn-north-1
          - Fn::Equals:
              - Ref: AWS::Region
              - cn-northwest-1
      - Fn::Or:
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-central-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-north-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-west-1
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-west-2
          - Fn::Equals:
              - Ref: AWS::Region
              - eu-west-3
          - Fn::Equals:
              - Ref: AWS::Region
              - me-south-1
          - Fn::Equals:
              - Ref: AWS::Region
              - sa-east-1
          - Fn::Equals:
              - Ref: AWS::Region
              - us-east-1
          - Fn::Equals:
              - Ref: AWS::Region
              - us-east-2
      - Fn::Or:
          - Fn::Equals:
              - Ref: AWS::Region
              - us-west-1
          - Fn::Equals:
              - Ref: AWS::Region
              - us-west-2

