DEV Community

Arun Kumar for AWS Community Builders

Posted on

How to tunnel to RDS without needing ec2 keypair

Goals

  • Don’t require using ec2 keypair (ec2-user)
  • Securely connect to your RDS database using a desktop client

Solution

  • Install and run the “socat” tool on one of your application’s ec2 hosts
  • Use SSM to forward the socat port to your local machine
  • Run your desktop client and connect to your RDS database

Details

a. Setting up socat on ec2

  • SSH to appls ec2
AWS_PROFILE=<saml-profile> aws ssm start-session — target “i-015b2a998123dsdsa4”
Enter fullscreen mode Exit fullscreen mode
  • Test connectivity (SG ingress) is correct for your ec2 server

  • Using release DNS record for your RDS database (release your builds!)

curl -v telnet://<app-host>:1521

# Use socat to open a port up on i-015b2a998123dsdsa4

sudo yum install -y socat
sudo nohup socat tcp-l:9521,fork,reuseaddr tcp:<app-host>:1521 &

# Tunnel using socat + ssm port forward

AWS_PROFILE=<saml-profile> aws ssm start-session — target i-015b2a998123dsdsa4 \
 — document-name AWS-StartPortForwardingSession \
 — parameters ‘{“portNumber”:[“9521”],”localPortNumber”:[“9521”]}’
Enter fullscreen mode Exit fullscreen mode

b. Get your credentials from AWS Secrets Manager (using your app ec2):

aws secretsmanager get-secret-value --region ap-southeast-1 --secret-id <secret-name> | jq -r .SecretString | jq
{
"password": "samplepwd",
"dbname": "demo-db",
"engine": "oracle",
"port": 1521,
"host": <db-host>,
"username": "root"
}
Enter fullscreen mode Exit fullscreen mode

c. Test using SQL Developer.

Note: In your terminal, you’ll see a few log lines when you open/connect to your forwarded port:

Starting session with SessionId: botocore-session-1579056167-0c76865253a1232e
Port 9521 opened for sessionId botocore-session-1579056167-0c76865253a1232e.
Connection accepted for session botocore-session-1579056167-0c76865253a1232e.
Enter fullscreen mode Exit fullscreen mode

And there you go. You can now see the data in SQL Developer !

Top comments (0)