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:
JavaScript
x
16
16
1
from ssh_pymongo import MongoSession
2
3
session = MongoSession(
4
host='ec2-x-x-x-x.region.compute.amazonaws.com',
5
port=22,
6
user='ec2-user', # The user ec2-user is specific to EC2 instance OS Amazon Linux 2
7
key='key.pem',
8
uri='mongodb://<username>:<password>@xxxxx-docdb-cluster.cluster-xxxxxxxxxxxxx.region.docdb.amazonaws.com:27017'
9
)
10
11
# Note for the above function call: I've also tried various combinations of the to_host and to_port params without success.
12
13
db = session.connection['db-name']
14
15
print(db.collection_names())
16
Error:
JavaScript
1
2
1
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.
2
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
JavaScript
1
36
36
1
from sshtunnel import SSHTunnelForwarder
2
from pymongo import MongoClient
3
4
# VM IP/DNS - Will depend on your VM
5
EC2_URL = '''*.*.compute.amazonaws.com'''
6
7
# Mongo URI Will depende on your DocDB instances
8
DB_URI = '''dbname.*.*.docdb.amazonaws.com'''
9
10
# DB user and password
11
DB_USER = 'dbuser'
12
DB_PASS = 'dbpassword'
13
14
# Create the tunnel
15
server = SSHTunnelForwarder(
16
(EC2_URL, 22),
17
ssh_username='ubuntu', # I used an Ubuntu VM, it will be ec2-user for you
18
ssh_pkey='~/.ssh/keypair.pem', # I had to give the full path of the keyfile here
19
remote_bind_address=(DB_URI, 27017),
20
local_bind_address=('127.0.0.1', 27017)
21
)
22
# Start the tunnel
23
server.start()
24
25
# Connect to Database
26
client = MongoClient(
27
host='127.0.0.1',
28
port=27017,
29
username='DB_USER',
30
password='DB_PASS'
31
)
32
33
34
# Close the tunnel once you are done
35
server.stop()
36