When you start using AWS RDS, you might end up creating a new database that is publicly accessible to start playing with it quickly. When it comes to security, having a public accessible DB is a bad idea. So, in this guide, we will show you, how to migrate a public RDS DB to be private without losing any data.
We have an API deployed to Amazon EC2 that is using a RDS Database that was created publicly accessible and we want to make it private.
Create a new route table without internet gateway association. Go to VPC → Route Tables
Put a descriptive name to the Route Table created to identify it
Create two new subnets and add them to the route table created in the previous step. Go to VPC → Subnets
If you don’t know how to setup Subnet CIDR, verify the pattern that is being used on the other subnets. For further information you can read this post.
After this step if you try to associate the new subnet group to your RDS DB you will receive the following error:
You cannot move DB instance XXX to subnet group XXX. The specified DB subnet group and DB instance are in the same VPC. Choose a DB subnet group in different VPC than the specified DB instance and try again. (Service: AmazonRDS; Status Code: 400; Error Code: InvalidVPCNetworkStateFault; Request ID: 7d46c84c-b22a-11e6-be20-b5bb6bd6cc6d)
Workaround for previous error:
Be careful with this last step, as you can delete unwanted VPC
As the DB is private now, the only way that a developer can connect to the DB for development purposes is using a tunnel connection from another AWS accessible asset. In this case, we will use the EC2 machine where the application is deployed to establish an SSH tunnel to the DB
Troubleshooting tip. If it fails to connect, check the security group of the EC2 machine to verify that the DB port is allowed.