Skip to content

Instantly share code, notes, and snippets.

@amalgjose
Forked from riddhi89/connect_private_rds.py
Created March 22, 2022 06:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save amalgjose/d046d637450d69739ccbba33d743a08d to your computer and use it in GitHub Desktop.
Save amalgjose/d046d637450d69739ccbba33d743a08d to your computer and use it in GitHub Desktop.
Connecting to a private AWS RDS instance in python
from sshtunnel import SSHTunnelForwarder
import pymysql
with SSHTunnelForwarder(
('ec2-52-202-194-76.public-ec2-instance.amazonaws.com'),
ssh_username="ec2-user",
ssh_pkey="~/ssh-tunnel-rds.pem",
remote_bind_address=('private-rds-instance.ckfkidfytpr4.us-east-1.rds.amazonaws.com', 3306)
) as tunnel:
print("****SSH Tunnel Established****")
db = pymysql.connect(
host='127.0.0.1', user="rdsuser",
password="rdspassword", port=tunnel.local_bind_port
)
# Run sample query in the database to validate connection
try:
# Print all the databases
with db.cursor() as cur:
cur.execute('SHOW DATABASES')
for r in cur:
print(r)
finally:
db.close()
print("YAYY!!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment