Skip to content
Advertisement

Python SSH tunnel into EC2 and connect to DocumentDB

I have been attempting to SSH tunnel into an EC2 instance and connect to DocumentDB that is located in the same VPC. I’ve tried all of the solutions I could dig up online with no luck. I am using the ssh_pymongo module, which wraps SSHTunnelForwarder. I am able to SSH directly into the EC2 instance and connect to the DocumentDB cluster. I’m trying to achieve this same thing via python.

Example code:

from ssh_pymongo import MongoSession

session = MongoSession(
    host='ec2-x-x-x-x.region.compute.amazonaws.com',
    port=22,
    user='ec2-user', # The user ec2-user is specific to EC2 instance OS Amazon Linux 2
    key='key.pem',
    uri='mongodb://<username>:<password>@xxxxx-docdb-cluster.cluster-xxxxxxxxxxxxx.region.docdb.amazonaws.com:27017'
)

# Note for the above function call: I've also tried various combinations of the to_host and to_port params without success.

db = session.connection['db-name']

print(db.collection_names())

Error:

Could not establish connection from local ('127.0.0.1', 36267) to remote ('xxxxx-docdb-cluster.cluster-xxxxxxxxxxxx.region.docdb.amazonaws.com', 27017) side of the tunnel: open new channel ssh error: Timeout opening channel.

Advertisement

Answer

I also tried the ssh_pymongo module but was unsuccessful. However I tried directly with the sshtunnel module and I was able to query my database.

Here is my code

from sshtunnel import SSHTunnelForwarder
from pymongo import MongoClient

# VM IP/DNS - Will depend on your VM
EC2_URL = '''*.*.compute.amazonaws.com'''

# Mongo URI Will depende on your DocDB instances
DB_URI = '''dbname.*.*.docdb.amazonaws.com'''

# DB user and password
DB_USER = 'dbuser'
DB_PASS = 'dbpassword'

# Create the tunnel
server = SSHTunnelForwarder(
    (EC2_URL, 22),
    ssh_username='ubuntu',                # I used an Ubuntu VM, it will be ec2-user for you
    ssh_pkey='~/.ssh/keypair.pem',   # I had to give the full path of the keyfile here
    remote_bind_address=(DB_URI, 27017),
    local_bind_address=('127.0.0.1', 27017)
)
# Start the tunnel
server.start()

# Connect to Database
client = MongoClient(
    host='127.0.0.1',
    port=27017,
    username='DB_USER',
    password='DB_PASS'
)


# Close the tunnel once you are done
server.stop()
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement