Home > Blockchain >  How to use python to connect to Postgresql RDS in Private subnet
How to use python to connect to Postgresql RDS in Private subnet

Time:09-16

I have my RDS(Postgresql) database in Private subnet. I want to query this db using a Python Program Is this possible ? I have a bastion running SSM and I can easily connect to the bastion without any keys and then connect to the DB. Is there a way of doing port forwarding in a python program ?

THANKS

CodePudding user response:

I followed this article -

https://aws.amazon.com/blogs/aws/new-port-forwarding-using-aws-system-manager-sessions-manager/

I am able to start the session with my ec2 - but the session is waiting for connections -

aws ssm start-session --target $INSTANCE_ID \
                       --document-name AWS-StartPortForwardingSession \
                       --parameters '{"portNumber":["80"],"localPortNumber":["9999"]}'

Starting session with SessionId: <cccccc-12cdddd> 
Port 9999 opened for sessionId <fffdggdgggg> 
Waiting for connections...

How can I now run , starting another terminal is not helping

psql -h <> .....

CodePudding user response:

Actually, it very simple if you use the article - https://aws.amazon.com/blogs/aws/new-port-forwarding-using-aws-system-manager-sessions-manager/

just run,

aws ssm start-session --target $INSTANCE_ID

this will create a connection to the ec2. After this you can run any python program by using psycopg2

import psycopg2 
connection = psycopg2.connect(user="joe",
                              password="joe",
                              host="######",
                              port="5432",
                              database="stackdb")

Just putting here as it might help someone

  • Related