---
## Amazon RDS Labs for MariaDB
## Infrastructure template with an RDS MariaDB Instance for lab exercises

AWSTemplateFormatVersion: 2010-09-09
Description: Amazon RDS Labs for MariaDB

## Mappings
Mappings:
  RegionalSettings:
    us-east-1:
      bastionAmi: ami-0b49a4a6e8e22fa16
      bastionType: m6g.large
      nodeType: db.r6g.large
      name: N. Virginia
      azs: "3"
    us-east-2:
      bastionAmi: ami-02af65b2d1ebdfafc
      bastionType: m6g.large
      nodeType: db.r6g.large
      name: Ohio
      azs: "3"
    us-west-1:
      bastionAmi: ami-039da1612f6f41296
      bastionType: m6g.large
      nodeType: db.r6g.large
      name: N. California
      azs: "2"
    us-west-2:
      bastionAmi: ami-078278691222aee06
      bastionType: m6g.large
      nodeType: db.r6g.large
      name: Oregon
      azs: "3"
    ca-central-1:
      bastionAmi: ami-04e842c4cdd82c62e
      bastionType: m6g.large
      nodeType: db.r6g.large
      name: Montreal
      azs: "2"
    eu-central-1:
      bastionAmi: ami-0b168c89474ef4301
      bastionType: m6g.large
      nodeType: db.r6g.large
      name: Frankfurt
      azs: "3"
    eu-west-1:
      bastionAmi: ami-0c0a42948ea1b4f44
      bastionType: m6g.large
      nodeType: db.r6g.large
      name: Ireland
      azs: "3"
    eu-west-2:
      bastionAmi: ami-0100b57d679daec93
      bastionType: m6g.large
      nodeType: db.r6g.large
      name: London
      azs: "3"
    eu-west-3:
      bastionAmi: ami-0df2138f920780ecc
      bastionType: m6g.large
      nodeType: db.r6g.large
      name: Paris
      azs: "3"
    ap-southeast-1:
      bastionAmi: ami-03d20fc12884694ee
      bastionType: m6g.large
      nodeType: db.r6g.large
      name: Singapore
      azs: "3"
    ap-southeast-2:
      bastionAmi: ami-07ef508d01f533f5f
      bastionType: m6g.large
      nodeType: db.r6g.large
      name: Sydney
      azs: "3"
    ap-south-1:
      bastionAmi: ami-0491e5015eb6e7a9b
      bastionType: m6g.large
      nodeType: db.r6g.large
      name: Mumbai
      azs: "3"
    ap-northeast-1:
      bastionAmi: ami-0fe0d4d94786add8e
      bastionType: m6g.large
      nodeType: db.r6g.large
      name: Tokyo
      azs: "3"
    ap-northeast-2:
      bastionAmi: ami-03665e633d23b2df6
      bastionType: m6g.large
      nodeType: db.r6g.large
      name: Seoul
      azs: "3"
  NetworkSettings:
    global:
      vpcCidr: 172.31.0.0/16
      subPub1Cidr: 172.31.0.0/24
      subPub2Cidr: 172.31.1.0/24
      subPub3Cidr: 172.31.2.0/24
      subPrv1Cidr: 172.31.10.0/24
      subPrv2Cidr: 172.31.11.0/24
      subPrv3Cidr: 172.31.12.0/24
      sshSourceCidr: 0.0.0.0/0
  InstanceSettings:
    global:
      dbSchema: mylab
      dbDriver: mysql
    scaling:
      maxCapacity: 2
      minCapacity: 1
      cpuLoadTarget: 20
    sysbench:
      dbSchema: sbtpcc
      runTime: '300'
      numThreads: '4'
      numTables: '8'
      numWarehouses: '2'


## Resources
Resources:

## The VPC
  vpc:
    Type: AWS::EC2::VPC
    Properties:
      EnableDnsSupport: true
      EnableDnsHostnames: true
      InstanceTenancy: default
      CidrBlock: !FindInMap [ NetworkSettings, global, vpcCidr ]
      Tags:
        - Key: Name
          Value: labstack-vpc

## Create an IGW & attach it to the VPC
  vpcIgw:
    Type: AWS::EC2::InternetGateway
    Properties:
      Tags:
        - Key: Name
          Value: labstack-igw
  attachIgwVpc:
    Type: AWS::EC2::VPCGatewayAttachment
    Properties:
      VpcId: !Ref vpc
      InternetGatewayId: !Ref vpcIgw

## Create a public subnet in each AZ
  sub1Public:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref vpc
      CidrBlock: !FindInMap [ NetworkSettings, global, subPub1Cidr ]
      AvailabilityZone: !Select 
        - 0
        - !GetAZs ""
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: labstack-pub-sub-1
  sub2Public:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref vpc
      CidrBlock: !FindInMap [ NetworkSettings, global, subPub2Cidr ]
      AvailabilityZone: !Select 
        - 1
        - !GetAZs ""
      MapPublicIpOnLaunch: true
      Tags:
        - Key: Name
          Value: labstack-pub-sub-2

## Associate the public subnets with a public route table
  rtbPublic:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
      Tags:
        - Key: Name
          Value: labstack-public-rtb
  rteToIgw:
    Type: AWS::EC2::Route
    DependsOn: attachIgwVpc
    Properties:
      RouteTableId: !Ref rtbPublic
      DestinationCidrBlock: 0.0.0.0/0
      GatewayId: !Ref vpcIgw
  srta1Public:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref sub1Public
      RouteTableId: !Ref rtbPublic
  srta2Public:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref sub2Public
      RouteTableId: !Ref rtbPublic

## Create a private subnet in each AZ
  sub1Private:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref vpc
      CidrBlock: !FindInMap [ NetworkSettings, global, subPrv1Cidr ]
      AvailabilityZone: !Select 
        - 0
        - !GetAZs ""
      MapPublicIpOnLaunch: false
      Tags:
        - Key: Name
          Value: labstack-prv-sub-1
  sub2Private:
    Type: AWS::EC2::Subnet
    Properties:
      VpcId: !Ref vpc
      CidrBlock: !FindInMap [ NetworkSettings, global, subPrv2Cidr ]
      AvailabilityZone: !Select 
        - 1
        - !GetAZs ""
      MapPublicIpOnLaunch: false
      Tags:
        - Key: Name
          Value: labstack-prv-sub-2

## Create a NAT Gateway & EIP
  natEip:
    Type: AWS::EC2::EIP
    Properties:
      Domain: vpc
  vpcNgw:
    Type: AWS::EC2::NatGateway
    DependsOn: attachIgwVpc
    Properties:
      AllocationId: !GetAtt natEip.AllocationId
      SubnetId: !Ref sub2Public

## Associate the private subnets with a NATed route table
  rtbNat:
    Type: AWS::EC2::RouteTable
    Properties:
      VpcId: !Ref vpc
      Tags:
        - Key: Name
          Value: labstack-nat-rtb
  rteToNgw:
    Type: AWS::EC2::Route
    Properties:
      RouteTableId: !Ref rtbNat
      DestinationCidrBlock: 0.0.0.0/0
      NatGatewayId: !Ref vpcNgw
  srta1Ngw:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref sub1Private
      RouteTableId: !Ref rtbNat
  srta2Ngw:
    Type: AWS::EC2::SubnetRouteTableAssociation
    Properties:
      SubnetId: !Ref sub2Private
      RouteTableId: !Ref rtbNat

## Create VPC S3 endpoint
  s3Enpoint:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      VpcId: !Ref vpc
      ServiceName: !Sub com.amazonaws.${AWS::Region}.s3
      RouteTableIds:
        - !Ref rtbPublic
        - !Ref rtbNat
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Principal: '*'
            Effect: 'Allow'
            Action: 's3:*'
            Resource: [ 'arn:aws:s3:::*', 'arn:aws:s3:::*/*' ]

## Create DB subnet group
  dbSubnets:
    Type: AWS::RDS::DBSubnetGroup
    Properties:
      DBSubnetGroupDescription: labstack-db-subnet-group
      SubnetIds: [ !Ref sub1Private, !Ref sub2Private ]
      Tags:
        - Key: Name
          Value: labstack-db-subnet-group

## Create bastion security group
  bastionSecGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      VpcId: !Ref vpc
      GroupName: labstack-bastion-host
      GroupDescription: RDS Lab SSH Security Group
      Tags:
        - Key: Name
          Value: labstack-bastion-host
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 22
          ToPort: 22
          CidrIp: !FindInMap [ NetworkSettings, global, sshSourceCidr ]
          Description: Allows SSH access from anywhere

## Create DB security group
  dbSecGroupInstance:
    Type: AWS::EC2::SecurityGroup
    Properties:
      VpcId: !Ref vpc
      GroupName: labstack-mariadb-internal
      GroupDescription: RDS Lab Database Firewall
      Tags:
        - Key: Name
          Value: labstack-mariadb-internal
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 3306
          ToPort: 3306
          SourceSecurityGroupId: !Ref bastionSecGroup
          Description: Allows MairaDB access from bastion host

## Create fault injection role to call Aurora RDS APIs and CW Logs
  roleFaultInjection:
      Type: "AWS::IAM::Role"
      Properties:
        RoleName: MariaDB-fis
        Description: "Allows FIS service to call Failover and Reboot APIs. Also push logs to CW logs."
        AssumeRolePolicyDocument:
          Version: 2012-10-17
          Statement:
            - Effect: Allow
              Action:
                - "sts:AssumeRole"
              Principal:
                Service:
                  - "fis.amazonaws.com"
        ManagedPolicyArns:
          - "arn:aws:iam::aws:policy/service-role/AWSFaultInjectionSimulatorRDSAccess"
          - "arn:aws:iam::aws:policy/AmazonSSMFullAccess"
        Policies:
          - PolicyName: inline-policy-fis
            PolicyDocument:
              Version: 2012-10-17
              Statement:
                - Effect: Allow
                  Action:
                    - "logs:PutResourcePolicy"
                    - "logs:DescribeResourcePolicies"
                    - "logs:DescribeLogGroups"
                    - "logs:CreateLogStream"
                    - "logs:CreateLogDelivery"
                    - "logs:CreateLogGroup"
                    - "logs:DeleteLogGroup"
                    - "logs:DeleteLogStream"
                    - "logs:CreateLogStream"
                    - "logs:DeleteLogDelivery"
                  Resource:
                    - "*"
        Tags:
          - Key: Name
            Value: MariaDB-fis

## Create enhanced monitoring role
  roleEnhancedMonitoring:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub labstack-monitor-${AWS::Region}
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - sts:AssumeRole
            Principal:
              Service:
                - monitoring.rds.amazonaws.com
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/service-role/AmazonRDSEnhancedMonitoringRole

## Create role for bastion host
  roleBastionHost:
    Type: AWS::IAM::Role
    Properties:
      RoleName: !Sub labstack-bastion-${AWS::Region}
      AssumeRolePolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Action:
              - 'sts:AssumeRole'
            Principal:
              Service:
                - 'ec2.amazonaws.com'
                - 'ssm.amazonaws.com'
      ManagedPolicyArns:
        - 'arn:aws:iam::aws:policy/service-role/AmazonEC2RoleforSSM'
      Policies:
        - PolicyName: inline-policy
          PolicyDocument:
            Version: 2012-10-17
            Statement:
              - Effect: Allow
                Action:
                  - rds:*
                  - s3:*
                  - ssm:*
                  - kms:*
                  - secretsmanager:*
                  - rds-db:connect
                Resource: "*"
  profileBastionHost:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Path: /
      Roles:
        - Ref: roleBastionHost

## Create the bastion host
  bastionHost:
    Type: AWS::EC2::Instance
    Properties:
      SubnetId: !Ref sub1Public
      InstanceType: !FindInMap [ RegionalSettings, !Ref "AWS::Region", bastionType ]
      SecurityGroupIds: [ !Ref bastionSecGroup ]
##      KeyName: !Ref ec2KeyPair
      Tags:
        - Key: Name
          Value: labstack-bastion-host
      BlockDeviceMappings:
        - DeviceName: /dev/sda1
          Ebs:
            DeleteOnTermination: true
            Iops: 7500
            VolumeSize: 150
            VolumeType: io1
      ImageId: !FindInMap [ RegionalSettings, !Ref "AWS::Region", bastionAmi ]
      IamInstanceProfile: !Ref profileBastionHost
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash -xe

          # update & upgrade packages
          apt-get update
          DEBIAN_FRONTEND=noninteractive apt-get -y -o Dpkg::Options::="--force-confdef" -o Dpkg::Options::="--force-confold" dist-upgrade
          echo "* updated and upgraded packages" >> /debug.log

          # update SSM agent
          snap remove amazon-ssm-agent
          wget https://s3.amazonaws.com/ec2-downloads-windows/SSMAgent/latest/debian_arm64/amazon-ssm-agent.deb
          DEBIAN_FRONTEND=noninteractive dpkg -i amazon-ssm-agent.deb
          echo "* update ssm-agent to latest" >> /debug.log

          # install jq
          apt-get -y install jq
          echo "* installed jq package" >> /debug.log

          # install zip
          apt-get -y install zip
          echo "* installed zip package" >> /debug.log

          # install mysql client tools
          apt-get -y install mysql-client
          mysql --version >> /debug.log
          echo "* installed mysql-client package" >> /debug.log

          # install sysbench
          curl -s https://packagecloud.io/install/repositories/akopytov/sysbench/script.deb.sh | sudo bash
          apt-get update
          apt-get -y install sysbench
          sysbench --version >> /debug.log
          echo "* installed sysbench package" >> /debug.log

          # install percona tpcc-like test suite
          git clone https://github.com/Percona-Lab/sysbench-tpcc.git /home/ubuntu/sysbench-tpcc
          chown -R ubuntu:ubuntu /home/ubuntu/sysbench-tpcc
          echo "* cloned percona/sysbench-tpcc repo" >> /debug.log

          # download demo databases
          git clone https://github.com/datacharmer/test_db.git /home/ubuntu/samples
          chown -R ubuntu:ubuntu /home/ubuntu/samples
          echo "* cloned test databases repo" >> /debug.log

          # install python pip and aws cli
          apt-get -y install python3-pip
          pip3 install pymysql
          cd /home/ubuntu
          curl -O https://awsauroralabsmysql.com/scripts/loadtest.py
          chown -R ubuntu:ubuntu /home/ubuntu/loadtest.py
          echo "* pulled load test script" >> /debug.log

          # configure AWS CLI
          curl "https://awscli.amazonaws.com/awscli-exe-linux-aarch64.zip" -o "awscliv2.zip"
          unzip awscliv2.zip
          ./aws/install
          mkdir /home/ubuntu/.aws
          touch /home/ubuntu/.aws/config
          echo "[default]" >> /home/ubuntu/.aws/config
          echo "region = ${AWS::Region}" >> /home/ubuntu/.aws/config
          chown -R ubuntu:ubuntu /home/ubuntu/.aws/config
          echo "* configured aws cli" >> /debug.log

          # set DB cluster user and password as env variables
          export SECRETSTRING=`aws secretsmanager get-secret-value --secret-id ${secretInstanceMasterUser} --region ${AWS::Region} | jq -r '.SecretString'`
          export DBPASS=`echo $SECRETSTRING | jq -r '.password'`
          export DBUSER=`echo $SECRETSTRING | jq -r '.username'`
          echo "export DBPASS=\"$DBPASS\"" >> /home/ubuntu/.bashrc
          echo "export DBUSER=$DBUSER" >> /home/ubuntu/.bashrc
          echo "* db credentials initialized" >> /debug.log

          #Create proxyfailovertest.sh
          touch /home/ubuntu/proxyfailovertest.sh
          echo 'while true;do mysql -h$DBHOST  -u$DBUSER -p$DBPASS mylab  -e "select now() as Time;"; done' >> /home/ubuntu/proxyfailovertest.sh 
          chown -R ubuntu:ubuntu /home/ubuntu/proxyfailovertest.sh
          chmod +x /home/ubuntu/proxyfailovertest.sh

          # reboot
          echo "* bootstrap complete, rebooting" >> /debug.log
          shutdown -r now

# ## Create parameter groups for RDS Instance
#   pgNodeParams:
#     Type: AWS::RDS::DBParameterGroup
#     Properties:
#       Description: labstack-node-params
#       Family: "mariadb10.4"
#       Parameters:
#         innodb_stats_persistent_sample_pages: "256"
#         slow_query_log: "1"
#         long_query_time: "10"
#         log_output: FILE
#       Tags:
#         - Key: Name
#           Value: labstack-node-params

## Create parameter groups for RDS Instance
  pgNodeParams:
    Type: AWS::RDS::DBParameterGroup
    Properties:
      Description: labstack-node-params
      Family: "mariadb10.11"
      Parameters:
       innodb_buffer_pool_load_at_startup: "0"
       max_heap_table_size: "16384"
       sort_buffer_size: "32768"
       tmp_table_size: "1024"
       rds.optimized_writes: "OFF"
      Tags:
       - Key: Name
         Value: labstack-node-params

## Create parameter groups for RDS Optimized Performance Instance
  pgNodeParamsOpi:
    Type: AWS::RDS::DBParameterGroup
    Properties:
      Description: Labstack-opi-params
      Family: "mariadb10.11"
      Parameters:
       innodb_buffer_pool_load_at_startup: "0"
       max_heap_table_size: "16384"
       sort_buffer_size: "32768"
       tmp_table_size: "1024"
      Tags:
       - Key: Name
         Value: labstack-opi-params

# ## Create options group for RDS Instance
#   ogNodeOptions:
#     Type: AWS::RDS::OptionGroup
#     Properties:
#       EngineName: mariadb
#       MajorEngineVersion: "10.4"
#       OptionConfigurations:
#         -
#             OptionName: MARIADB_AUDIT_PLUGIN
#             OptionSettings:
#                 -
#                     Name: SERVER_AUDIT_EVENTS
#                     Value: "CONNECT,QUERY,QUERY_DDL,QUERY_DML,QUERY_DCL"
#       OptionGroupDescription: labstack-node-options
#       Tags:
#         - Key: Name
#           Value: labstack-node-options

## Create a random generated password and store it as a secret
  secretInstanceMasterUser:
    Type: AWS::SecretsManager::Secret
    Properties:
      Description: "Master user credentials for labstack-instance"
      GenerateSecretString:
        SecretStringTemplate: '{"username": "masteruser"}'
        GenerateStringKey: 'password'
        PasswordLength: 10
        ExcludeCharacters: '"@/\$`&'
      Tags:
        - Key: Name
          Value: labstack-secret

## Create RDS Instance
  dbInstance:
    Type: AWS::RDS::DBInstance
    Properties:
      Engine: MariaDB
      EngineVersion: "10.6.19"
      AllocatedStorage: 100
      DBSubnetGroupName: !Ref dbSubnets
      # DBParameterGroupName: !Ref pgNodeParams
      # OptionGroupName: !Ref ogNodeOptions
      DBInstanceIdentifier: labstack-instance
      DBInstanceClass: !FindInMap [ RegionalSettings, !Ref "AWS::Region", nodeType ]
      DBName: !FindInMap [ InstanceSettings, global, dbSchema ]
      BackupRetentionPeriod: 7
      MasterUsername: !Join ['', ['{{resolve:secretsmanager:', !Ref secretInstanceMasterUser, ':SecretString:username}}' ]]
      MasterUserPassword: !Join ['', ['{{resolve:secretsmanager:', !Ref secretInstanceMasterUser, ':SecretString:password}}' ]]
      MonitoringInterval: 1
      MonitoringRoleArn: !GetAtt roleEnhancedMonitoring.Arn
      PubliclyAccessible: false
      StorageType: io1
      Iops: 3000
      StorageEncrypted: true
      VPCSecurityGroups: [ !Ref dbSecGroupInstance ]
      EnableCloudwatchLogsExports: [ error, slowquery, audit ]
      EnableIAMDatabaseAuthentication: false
      EnablePerformanceInsights: true
      PerformanceInsightsRetentionPeriod: 7
      Tags:
        - Key: Name
          Value: labstack-instance

## Create RDS Optimized Performance Instance
  dbInstanceOp:
    Type: AWS::RDS::DBInstance
    Properties:
      Engine: MariaDB
      EngineVersion: "10.11.9"
      AllocatedStorage: 200
      DBSubnetGroupName: !Ref dbSubnets
      DBParameterGroupName: !Ref pgNodeParamsOpi
      # OptionGroupName: !Ref ogNodeOptions
      DBInstanceIdentifier: labstack-OptimizedPerformance
      DBInstanceClass: db.r6gd.4xlarge
      DBName: !FindInMap [ InstanceSettings, global, dbSchema ]
      BackupRetentionPeriod: 7
      MasterUsername: !Join ['', ['{{resolve:secretsmanager:', !Ref secretInstanceMasterUser, ':SecretString:username}}' ]]
      MasterUserPassword: !Join ['', ['{{resolve:secretsmanager:', !Ref secretInstanceMasterUser, ':SecretString:password}}' ]]
      MonitoringInterval: 1
      MonitoringRoleArn: !GetAtt roleEnhancedMonitoring.Arn
      MultiAZ: true
      PubliclyAccessible: false
      StorageType: io1
      Iops: 3000
      StorageEncrypted: true
      VPCSecurityGroups: [ !Ref dbSecGroupInstance ]
      EnableCloudwatchLogsExports: [ error, slowquery, audit ]
      EnableIAMDatabaseAuthentication: false
      EnablePerformanceInsights: true
      PerformanceInsightsRetentionPeriod: 7
      Tags:
        - Key: Name
          Value: labstack-optimized-performance-instance

## Create RDS NON Optimized Performance Instance
  dbInstancenonopi:
    Type: AWS::RDS::DBInstance
    Properties:
      Engine: MariaDB
      EngineVersion: "10.11.9"
      AllocatedStorage: 200
      DBSubnetGroupName: !Ref dbSubnets
      # DBParameterGroupName: !Ref pgNodeParamsOpi
      # OptionGroupName: !Ref ogNodeOptions
      DBInstanceIdentifier: labstack-nonoptimized
      DBInstanceClass: db.r5.4xlarge
      DBName: !FindInMap [ InstanceSettings, global, dbSchema ]
      BackupRetentionPeriod: 7
      MasterUsername: !Join ['', ['{{resolve:secretsmanager:', !Ref secretInstanceMasterUser, ':SecretString:username}}' ]]
      MasterUserPassword: !Join ['', ['{{resolve:secretsmanager:', !Ref secretInstanceMasterUser, ':SecretString:password}}' ]]
      MonitoringInterval: 1
      MonitoringRoleArn: !GetAtt roleEnhancedMonitoring.Arn
      MultiAZ: true
      PubliclyAccessible: false
      StorageType: io1
      Iops: 3000
      StorageEncrypted: true
      VPCSecurityGroups: [ !Ref dbSecGroupInstance ]
      EnableCloudwatchLogsExports: [ error, slowquery, audit ]
      EnableIAMDatabaseAuthentication: false
      EnablePerformanceInsights: true
      PerformanceInsightsRetentionPeriod: 7
      Tags:
        - Key: Name
          Value: labstack-nonoptimized

## Create sysbench prep SSM document
  ssmDocSysbenchTest:
    Type: AWS::SSM::Document
    Properties:
      DocumentType: Command
      Tags:
        - Key: Name
          Value: labstack-sysbench-test
      Content:
        schemaVersion: '2.2'
        description: SysBench Percona TPCC-LIKE Preparation
        parameters:
          instanceEndpoint:
            type: String
            description: RDS MariaDB Instance Endpoint
            default: !GetAtt dbInstance.Endpoint.Address
          dbUser:
            type: String
            description: DB User
            default: !Join ['', ['{{resolve:secretsmanager:', !Ref secretInstanceMasterUser, ':SecretString:username}}' ]]
          dbPassword:
            type: String
            description: DB Password
            default: !Join ['', ['{{resolve:secretsmanager:', !Ref secretInstanceMasterUser, ':SecretString:password}}' ]]
          dbSchema:
            type: String
            description: DB Schema
            default: !FindInMap [ InstanceSettings, sysbench, dbSchema ]
          dbDriver:
            type: String
            description: DB Driver
            default: !FindInMap [ InstanceSettings, global, dbDriver ]
            allowedValues: [ mysql, pgsql ]
          runTime:
            type: String
            description: Test Runtime
            default: !FindInMap [ InstanceSettings, sysbench, runTime ]
          numThreads:
            type: String
            description: Threads
            default: !FindInMap [ InstanceSettings, sysbench, numThreads ]
          numTables:
            type: String
            description: Tables
            default: !FindInMap [ InstanceSettings, sysbench, numTables ]
          numScale:
            type: String
            description: Scale
            default: !FindInMap [ InstanceSettings, sysbench, numWarehouses ]
        mainSteps:
        - action: aws:runShellScript
          name: SysBenchTpccPrepare
          inputs:
            runCommand:
            - 'echo "DROP SCHEMA IF EXISTS {{ dbSchema }}; CREATE SCHEMA {{ dbSchema }};" | mysql -h{{ instanceEndpoint }} -u{{ dbUser }} -p"{{ dbPassword }}" && cd /home/ubuntu/sysbench-tpcc && ./tpcc.lua --mysql-host={{ instanceEndpoint }} --mysql-user={{ dbUser }} --mysql-password="{{ dbPassword }}" --mysql-db={{ dbSchema }} --threads={{ numThreads }} --tables={{ numTables }} --scale={{ numScale }} --time={{ runTime }} --db-driver={{ dbDriver }} prepare'
        - action: aws:runShellScript
          name: SysBenchTpccRun
          inputs:
            runCommand:
            - 'cd /home/ubuntu/sysbench-tpcc && ./tpcc.lua --mysql-host={{ instanceEndpoint }} --mysql-user={{ dbUser }} --mysql-password="{{ dbPassword }}" --mysql-db={{ dbSchema }} --threads={{ numThreads }} --tables={{ numTables }} --scale={{ numScale }} --time={{ runTime }} --db-driver={{ dbDriver }} run'

## Outputs
Outputs:
  vpcId:
    Description: RDS MariaDB Lab VPC
    Value: !Ref vpc
  bastionInstance:
    Description: Bastion Instance ID
    Value: !Ref bastionHost
  instanceName:
    Description: Instance Name
    Value: !Ref dbInstance
  instanceEndpoint:
    Description: RDS MariaDB Instance Endpoint
    Value: !GetAtt dbInstance.Endpoint.Address
  loadTestRunDoc:
    Description: Load Test Execution Command Document
    Value: !Ref ssmDocSysbenchTest
  dbSubnetGroup:
    Description: Database Subnet Group
    Value: !Ref dbSubnets
  dbSecurityGroup:
    Description: Database Security Group
    Value: !Ref dbSecGroupInstance
  secretArn:
    Description: Database Credentials Secret ARN
    Value: !Ref secretInstanceMasterUser
