How to create an RDS Database in AWS using CDK for Python

Felix Mulei
3 min readNov 10, 2023

--

In the previous demo, we created a custom VPC and established a vpc peering using AWS CDK for python. Today we will be creating an RDS database and connect it to remotely from the terminal remotely.

The first step is to create a directory you will be working from and then initiate the application.

cdk init app --language python

Now you can create your custom VPC in which you will be creating the database in. (This code is similar to the one in the previous project.

       custom_vpc = ec2.Vpc(
self, "customvpc",
ip_addresses= ec2.IpAddresses.cidr(Prod_configs['vpc_config']['vpc_cidr']),
max_azs= 2,
subnet_configuration=[
ec2.SubnetConfiguration(
name="PublicSubnet", cidr_mask=Prod_configs["vpc_config"]["cidr_mask"], subnet_type=ec2.SubnetType.PUBLIC
),
ec2.SubnetConfiguration(
name="PrivateSubnet", cidr_mask=Prod_configs["vpc_config"]["cidr_mask"], subnet_type=ec2.SubnetType.PRIVATE_ISOLATED
),
])

After creating the VPC, now it's time to create the database. The database engine will be MySQL (but you can use any other engine). Because of testing connection remotely, the database should be in the public subnet (Not the best practice because of security). No multi-az and deletion protection will be disabled in our case (In production should be different). The database password will be auto generated and stored in the secrets manager. Here is the code

        #Create an RDS Database
myDB = rds.DatabaseInstance(self,
"MyDatabase",
engine= rds.DatabaseInstanceEngine.MYSQL,
vpc= custom_vpc,
vpc_subnets= ec2.SubnetSelection(
subnet_type= ec2.SubnetType.PUBLIC,
),
credentials= rds.Credentials.from_generated_secret("Admin"),
instance_type= ec2.InstanceType.of(ec2.InstanceClass.BURSTABLE3,
ec2.InstanceSize.MICRO),
port= 3306,
allocated_storage= 80,
multi_az= False,
removal_policy= remove.DESTROY,
deletion_protection= False,
publicly_accessible= True
)

To allow remote connectivity, we need to open port 3306. In this demo I'm opening from all ipv addresses.

        myDB.connections.allow_from_any_ipv4(
ec2.Port.tcp(3306),
description= "Open port for connection"
)

Last, we can request for the database endpoint.

        CfnOutput(self, 
"db_endpoint",
value= myDB.db_instance_endpoint_address)

Now that the code is ready, you can bootstrap the environment.

cdk bootstrap

The environment is ready. Next is the deployment

cdk deploy

Everything is done. Here is the secrets manager with our credentials

Now we can now test connectivity to the database.

mysql -u Admin -h rdsstack-mydatabase1e2517db-gmgf5rgagc7t.cuzfhplb4dbn.eu-west-2.rds.amazonaws.com -p

Everthing is working well. So, we have managed to create a database using CDK for python and tested the connectivity.

Thank you.

Here is the GITHUB REPO

--

--