Use Port Forwarding to access DB on Cloud

2022年09月15日


Launch an EC2 instance using Amazon Linux 2.

Install socat and create a bidirectional byte stream from the EC2 instance to RDS:

#!/bin/bash
set -o xtrace
yum install -y socat
socat TCP-LISTEN:3306,reuseaddr,fork TCP4:<RDS-endpoint>:3306

For example:
#!/bin/bash
set -o xtrace
yum install -y socat
socat TCP-LISTEN:3306,reuseaddr,fork TCP4:example.cluster-xxxx.us-west-2.rds.amazonaws.com:3306

Provision a test Linux machine.
#!/bin/bash
set -o xtrace
aws configure set default.region us-west-2
curl "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/linux_64bit/session-manager-plugin.rpm" -o "session-manager-plugin.rpm"
yum install -y session-manager-plugin.rpm
yum install -y mysql

Open one terminal to access the test machine. And execute below command.
aws ssm start-session --target <id-of-an-instance> --document-name AWS-StartPortForwardingSession --parameters '{"portNumber":["3306"], "localPortNumber":["3306"]}'


Test:
Open another terminal to access the same test machine. And execute below command to access RDS.
mysql --port=3306 --host=127.0.0.1 -u some_user -p


If you need to access multiple targets, then use below user data.
#!/bin/bash
set -o xtrace
yum install -y socat
socat TCP-LISTEN:3306,reuseaddr,fork TCP4:example.cluster-xxxxx.us-west-2.rds.amazonaws.com:3306 | socat TCP-LISTEN:10022,reuseaddr,fork TCP4:10.0.111.222:22
Then provision another Linux machine, B.

Test result:
- You can access the same RDS from the test machine A and test machine B simutaneously.
- Both the RDS and the server for SSH (http://10.0.111.222) could be accessed simutaneously.
- If you stop the port forwarding from the test machine, and then establish the port forwarding again, you can still access RDS and the server after that.
 

References

AWS SSM Session Manager Port Forwarding to RDS without SSH


Category: AWS Tags: public

Upvote


Downvote