AWSTemplateFormatVersion: '2010-09-09'
Description: Development Database Stack
Parameters:
  EnvironmentName:
    Description: An environment name that is prefixed to resource names
    Type: String
  MasterPassword:
    Description: The master password for the database.
    Type: String
    
Resources:
  PrimaryDatabaseSubnet:
    Type: AWS::RDS::DBSubnetGroup
    Properties: 
      DBSubnetGroupDescription: The database subnet
      DBSubnetGroupName: !Sub primary-database-${EnvironmentName}
      SubnetIds: 
        - Fn::ImportValue:
            !Sub "${EnvironmentName}PublicSubnet1"
        - Fn::ImportValue:
            !Sub "${EnvironmentName}PublicSubnet2"
  PrimaryDatabase:
    Type: AWS::RDS::DBInstance
    Properties: 
      AllocatedStorage: 20
      AllowMajorVersionUpgrade: false
      AutoMinorVersionUpgrade: true
      AvailabilityZone: eu-west-1a
      BackupRetentionPeriod: 0
      CopyTagsToSnapshot: true
      DBInstanceClass: db.t3.micro
      DBInstanceIdentifier: !Sub heisenberg-${EnvironmentName}
      DBName: heisenberg
      DBSubnetGroupName: !Ref PrimaryDatabaseSubnet
      DeleteAutomatedBackups: true
      DeletionProtection: false
      Engine: mysql
      EngineVersion: 8.0.25
      MasterUsername: admin
      MasterUserPassword: !Sub ${MasterPassword}
      MultiAZ: false
      PubliclyAccessible: true
      StorageEncrypted: false
      StorageType: standard
      VPCSecurityGroups: 
        - Fn::ImportValue:
            !Sub "${EnvironmentName}DatabaseSecurityGroup"

Outputs:
  PrimaryDatabaseAddress:
    Value: !GetAtt PrimaryDatabase.Endpoint.Address
    Export:
      Name: !Sub "${EnvironmentName}PrimaryDatabaseAddress"
            