Enhance your project Makefile
in the project directory with the following content:
DATABASE_DB_NAME := javadockerawsexample
#########################################################
.PHONY: database
database: guard-STAGE
aws cloudformation deploy \
--no-fail-on-empty-changeset \
--template-file cloudformation/database.yml \
--stack-name $(SERVICE)-$(STAGE)-db \
--parameter-overrides DatabaseDbName=$(DATABASE_DB_NAME) \
--region $(AWS_REGION)
.PHONY: guard-%
guard-%:
$(if $(value ${*}),,$(error "Variable ${*} not set!"))
Create a new cloudformation template in cloudformation/database.yml
and define your database in there:
---
AWSTemplateFormatVersion: 2010-09-09
Description: Database resources for '...'
Parameters:
DatabaseDbName:
Type: String
Resources:
AuroraSubnetGroup:
Type: AWS::RDS::DBSubnetGroup
Properties:
DBSubnetGroupDescription: !Sub '${AWS::StackName}-db'
SubnetIds: !Split
- ','
- 'Fn::ImportValue': 'vpc-SubnetsPrivate'
AuroraClusterSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: !Sub '${AWS::StackName}-db'
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 3306
ToPort: 3306
CidrIp:
Fn::ImportValue: 'vpc-VPCCIDRBlock'
VpcId:
'Fn::ImportValue': 'vpc-VPC'
Tags:
- Key: Name
Value: !Sub '${AWS::StackName}-db'
AuroraCluster:
Type: AWS::RDS::DBCluster
Properties:
EngineMode: serverless
ScalingConfiguration:
AutoPause: true
MaxCapacity: 4
MinCapacity: 2
SecondsUntilAutoPause: 600
BackupRetentionPeriod: 1
DatabaseName: !Ref DatabaseDbName
DBClusterIdentifier: !Ref AWS::StackName
DBSubnetGroupName: !Ref AuroraSubnetGroup
Engine: aurora
MasterUsername: !Join ['', ['{{resolve:secretsmanager:', !Ref AuroraSecret, ':SecretString:username}}' ]]
MasterUserPassword: !Join ['', ['{{resolve:secretsmanager:', !Ref AuroraSecret, ':SecretString:password}}' ]]
VpcSecurityGroupIds:
- !Ref AuroraClusterSecurityGroup
AuroraSecret:
Type: "AWS::SecretsManager::Secret"
Properties:
Name: !Sub '${AWS::StackName}-db'
Description: "This is a Secrets Manager secret for the Aurora instance"
GenerateSecretString:
SecretStringTemplate: '{"username": "admin"}'
GenerateStringKey: "password"
PasswordLength: 16
ExcludeCharacters: '"@/\'
AuroraSecretAttachment:
Type: "AWS::SecretsManager::SecretTargetAttachment"
Properties:
SecretId: !Ref AuroraSecret
TargetId: !Ref AuroraCluster
TargetType: AWS::RDS::DBCluster
Create the Cloudformation stack with the following command in the app-staging AWS account
AWS_PROFILE=myorg-app-staging make database STAGE=dev