Opening multiple DB tunnels with AWS SSM
(2024-06-26)
[note]
To open a tunneled connection to an AWS managed database, such as RDS or DocumentDB, the commonly recommended way is to use a bastion host and aws ssm start-session. The bastion host is an EC2 instance that is in the same VPC as your database. The AWS CLI command allows you to connect to SSM-enabled EC2 instances from your development machine using IAM authorization, without having to manage SSH keys.
The script below connects to the specified PostgreSQL RDS and DocumentDB instances using a bastion host. Both databases will be accessible on a localhost port. Modify as necessary.
#!/bin/bash
# Configure to match your environment
BASTION_NAME="<YOUR_BASTION_INSTANCE_NAME>"
DOCDB_CLUSTER_NAME="<YOUR_DOCDB_CLUSTER_NAME>"
PG_CLUSTER_NAME="<YOUR_RDS_CLUSTER_NAME>"
DOCDB_PORT="27017"
PG_PORT="5432"
# Fail on errors, do not allow use of unset variables
# Colors for nicer output
BB="\\033[34m"
RST="\\033[0m"
# Fetch the endpoints URIs and bastion instance ID
DOCDB_ENDPOINT=
PG_ENDPOINT=
BASTION_INSTANCE=
# DocumentDB port forwarding
&
PID1=
# PostgreSQL port forwarding
&
PID2=
# Catch the interrupt signal (CTRL-C)
# Wait for both processes to exit
Jan Tuomi