Psycopg2 on AWS Lambda not connecting to RDS database

0

When I try to connect to my RDS Postgresql DB I get the following output

{
   "errorMessage": "2022-01-07T13:28:35.428Z 975a92cd-936c-4d1c-8c23-6318cd609bff Task timed out after 10.01 seconds"
}

The DB is set to public access

Lambda psycopg2 connection code

connection = psycopg2.connect(user=user,
                              password=password,
                              host=host,
                              port=port,
                              database=database)

print(connection)

<connection object at 0x7ff7eb854b90; dsn: 'user=db_user password=db_password dbname=db_name host=rds_host port=5432', closed: 0>

RDS_LAMBDA_SECURITY_GROUP Inbound Here

VPC Route Table Routes Here

Also all the subnets are associated to the route table

Lambda_Role permissions
Here

VPC Logs
Lots of REJECTED connections, not sure if it is safe to post a print here. Sometimes the connection to the DB is status ACCEPTED but there are a few other with REJECTED status

Any idea on why I still can't connect to my DB?

2 Answers
1

You mention that "the DB is set to public access". This means that the DNS Name of the database will resolve to a public IP address. Unfortunately, this means that the traffic will need to go out of the VPC and then back in again. It also means that the security groups cannot refer to each other, since this only permits access via private IP address.

For good security, you should not configure the database for 'public access'. The Lambda function will then resolve the database DNS Name to a private IP address, which should allow the connection.

So, you really have two options:

  1. Public database, Lambda function not connected to the VPC, security group permits access from entire Internet, or
  2. Private database, Lambda function connected to private subnet(s) of the same VPC as the RDS database, security group permits access from Lambda function's security group
answered 2 years ago
0

Does your Lambda security group have an egress rule for port 5432? Can you post your Lambda code? It's not clear to me where "errorMessage" and its contents are coming from.

EXPERT
answered 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions