简体   繁体   中英

How to use python to connect to Postgresql RDS in Private subnet

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

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 <> .....

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM