Search code examples
python-3.xpostgresqlamazon-rdsportforwardingssh-tunnel

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


Solution

  • 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