Connecting on AWS DocumentDB Through SSH Tunnel (command line tips)
Ilson Roberto M. Pereira
I take care of your databases, so you can focus on growing your business | PostgreSQL, MySQL, Oracle Database, Microsoft SQL Server, MongoDB w/ Terraform, Ansible @ AWS, Azure, OCI, GCP
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:
领英推荐
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.
I hope to be helpful. Even though the commands are simple, the process who requires it is not always so straight forward. Cheers!