Connecting on AWS DocumentDB Through SSH Tunnel (command line tips)

Connecting on AWS DocumentDB Through SSH Tunnel (command line tips)

As new technologies emerge and new tools are part of our daily lives, we are more and more tied to instruments and less and less to instrumentation.

In this guide I'll show you how to connect to an AWS DocumentDB through a SSH Tunnel via CLI (Command Line Interface).

This is important to know if you think the DocumentDB specifically doesn't accept connection directly from a public endpoint, such as your laptop or local development machine (the DocumentDB is a VPC-only open PaaS), so you must use a Bastion Host sharing the same VPC if you want to connect on your brand new NoSQL Database Cluster.

The DocumentDB is an AWS Database Service compatible with MongoDB, so this guide still applies to you if you are using MongoDB in an IaaS, for instance. Indeed, this guide applies to you if you have ever wondered how tools like DBeaver works behind the scenes when you are using the 'SSH Tunnel' option.

I'm assuming you are using a Linux or Mac environment, and for obvious reasons, all the IPs and Endpoints have been hidden. So, let's start!

All you need is love (and some simple commands)

The following command forwards your local 27017 port to the DocumentDB server (running on port 27017 as well):

[mymachine ~]$ ssh -i ~/.ssh/bastion-host.pem -L 27017:docdb-cluster.amazonaws.com:27017 [email protected] -Nf        

In the example:

  • -i (points to your ssh key)
  • -L (local TCP forwarding)
  • ec2-user (user of your Bastion Host)
  • 12.345.678.90 (IP of the Bastion Host)
  • -N (Don't execute a remote command. In other words, just forwards the port)
  • -f (go to background. This allows you to stay on the same CLI instead of opening a new window to work on your Mongo Shell)

After local forwarding your port as above, all you need is properly connect into your DocumentDB using localhost (127.0.0.1) instead the DocumentDB endpoint itself, as below:

[mymachine ~]$ mongosh 127.0.0.1:27017 --tlsAllowInvalidHostnames --tls --tlsCAFile ~/.ssh/rds-combined-ca-bundle.pem --username docdbuser --password docdbuserpasswd        

Closing the Tunnel

After finishing your work, you may wonder what happened with your background SSH command. In fact it will still be there until you end it. It is a tunnel from your local machine direct to the database server through the bridge-bastion-host. As a good tip to manage it, I like to use:

[mymachine ~]$ sudo netstat -nltp|grep 27017 && ps -ef|grep ssh        

It will show you if there is the 27017 port opened and the commands SSH running on your environment. You are free to kill the now-not-required-anymore process running in background.

All the process in a glance

I hope to be helpful. Even though the commands are simple, the process who requires it is not always so straight forward. Cheers!

要查看或添加评论,请登录

社区洞察

其他会员也浏览了