I’m relatively new to aws-cdk and aws infrastructure in general. I’ve been able to try to connect to my RDS database locally with no success. I was able to have my fargate cluster connect to the database. Here is my typescript aws-cdk code:
const vpc = new ec2.Vpc(this, 'TestVpc', {
maxAzs: 2, // Adjust the number of availability zones as needed
});
const clusterSecurityGroup = new ec2.SecurityGroup(
this,
'ClusterSecurityGroup',
{
vpc,
},
);
clusterSecurityGroup.addIngressRule(
ec2.Peer.ipv4(`${myIp}/32`),
ec2.Port.allTraffic(), // Replace with the desired port or specific port(s)
'Allow inbound access from specific IP',
);
const database = new rds.DatabaseInstance(this, 'TestDatabase', {
databaseName: 'myrnamethod',
engine: rds.DatabaseInstanceEngine.POSTGRES,
publiclyAccessible: true, // Allow public access
credentials: rds.Credentials.fromPassword(
process.env.DB_USERNAME as string,
cdk.SecretValue.unsafePlainText(process.env.DB_PASSWORD as string),
),
instanceType: ec2.InstanceType.of(
ec2.InstanceClass.T4G,
ec2.InstanceSize.MICRO,
),
vpc,
securityGroups: [clusterSecurityGroup],
});
const loadBalancedFargateService =
new ecsPatterns.ApplicationLoadBalancedFargateService(
this,
'TestService',
{
memoryLimitMiB: 512,
cpu: 256,
taskImageOptions: {
image: ecs.ContainerImage.fromAsset('../', {
file: 'Dockerfile',
}),
containerPort: 3000,
},
vpc,
securityGroups: [clusterSecurityGroup],
},
);
database.connections.allowFrom(
ec2.Peer.ipv4(`${myIp}/32`),
ec2.Port.allTraffic(),
'Allow inbound access from local machine',
);
database.connections.allowDefaultPortFrom(
loadBalancedFargateService.service,
'Allow inbound access from ECS Fargate service',
);
database.connections.allowFrom(
clusterSecurityGroup,
ec2.Port.tcp(database.instanceEndpoint.port),
'Allow inbound access from ECS cluster',
);
Can anyone point out what I’m doing wrong?
2
Answers
The easiest and most secure way I could find was to create an EC2 Instance in the same VPC and security group and then within RDS they have an area called
Connected compute resources
and you can connect that EC2 instance.Then you can SSH into it using a private key (select this option on generation of ec2 instance) and download postgres server/client within the server (or whichever databse) and connect through it. Here's the posgres installation instructions for amazon linux 2023 ec2 instances that I used:
https://devopscube.com/install-configure-postgresql-amazon-linux/
You need to place your DB in a public subnet so that it gets a public IP address. Omit the creation of security groups, let CDK handle that.
It is also worth noting that you are exposing your password in the cloudformation template in plaintext.