I have an EC2 instance (EC2_VM
) where I can connect mongodb (MONGO_HOST
)from
with sshtunnel.open_tunnel(
(EC2_VM, 22),
ssh_username="ec2-user",
ssh_pkey=EC2_KEY,
remote_bind_address=(MONGO_HOST, 27017),
local_bind_address=("0.0.0.0", 27017),
) as tunnel:
print(tunnel.local_bind_port)
# list database names
client = MongoClient(
"mongodb://%s:%s@%s" % (MONGO_USER, MONGO_PASSWORD, "127.0.0.1"),
port=tunnel.local_bind_port,
)
names = client.list_database_names()
print(names)
But I am getting below error. Any idea whats wrong here? It looks like it has set up the tunnel properly but cant seem to reach mongo still. TIA
File "/lib/python3.11/site-packages/pymongo/topology.py", line 269, in _select_servers_loop
raise ServerSelectionTimeoutError(
pymongo.errors.ServerSelectionTimeoutError: 127.0.0.1:27017: timed out, Timeout: 30s, Topology Description: <TopologyDescription id: 6530a0a24577402c25f1997e, topology_type: Unknown, servers: [<ServerDescription ('127.0.0.1', 27017) server_type: Unknown, rtt: None, error=NetworkTimeout('127.0.0.1:27017: timed out')>]>
anyone who has docdb set up in aws, how do you guys connect to it from localhost? It works with MongoDB Compass because it provides the ssh tunnel option from GUI but when I am trying to do it via script using pymongo, it's not working
TIA
This was fixed by supplying
directConnection=True
toMongoClient