There are multiple questions/answers for this but none of the solutions seem to work.
- How to properly connect AWS Lambda to RDS in VPC?
- Allow AWS Lambda to access RDS Database
- Can't access to RDS from Amazon Lambda, same VPC and correct role permissions
My current setup is:
- Lambda (with python 2.7 runtime) in VPC
- RDS instance (postgres) in same VPC
- Lambda role has policy read/write to certain S3 buckets and AWSLambdaVPCAccessExecutionRole
- Lambda subnet's route table has access to local IPs, and to a VPC endpoint for S3
- RDS subnet's route table has access to local IPs
- Lambda security group (SG) has inbound & outbound rules for Postgres & VPC endpoint
- RDS SG has inbound & outbound rules for the Lambda SG id
I'm using psycopg2 to connect, which is in my requirements.txt
file. I tried a simple SELECT query as below:
conn = psycopg2.connect(dbname=os.environ['DB_NAME'], user=os.environ['USERNAME'], password=os.environ['PASSWORD'])
cursor = conn.cursor()
query = "SELECT * from {};".format(os.environ['TABLE'])
cursor.execute(query)
records = cursor.fetchall()
Which gives me the error:
could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?
: OperationalError
Traceback (most recent call last):
File "/var/task/mylambda.py", line 31, in call
conn = psycopg2.connect(dbname=os.environ['DB_NAME'],
user=os.environ['USERNAME'], password=os.environ['PASSWORD'])
File "/tmp/sls-py-req/psycopg2/__init__.py", line 130, in connect
conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
What am I missing? How can I successfully connect to RDS from my Lambda? Thanks!