Cloud
SSM Portfowarding
All_is_LiJell
2025. 5. 20. 14:27
반응형
Intro
To enhance security, I’ve relocated the bastion instance from the public subnet to the private subnet.
Previously, we accessed the database using SSH connection, but moving forward, we will use SSM port forwarding instead.
prerequisite
1. SSM Plugin should be installed first
2. AmazonSSMManagedInstanceCore should be on EC2 instance role
3. requried permission on User as below
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowSSMSessionControl",
"Effect": "Allow",
"Action": [
"ssm:StartSession",
"ssm:ResumeSession",
"ssm:TerminateSession",
"ssm:DescribeSessions"
],
"Resource": [
"arn:aws:ssm:*:*:session/*",
"arn:aws:ec2:*:*:instance/*"
]
},
{
"Sid": "AllowPortForwardingDocs",
"Effect": "Allow",
"Action": [
"ssm:DescribeDocument"
],
"Resource": [
"arn:aws:ssm:*:*:document/AWS-StartPortForwardingSession",
"arn:aws:ssm:*:*:document/AWS-StartPortForwardingSessionToRemoteHost"
]
},
{
"Sid": "AllowInstanceInfo",
"Effect": "Allow",
"Action": [
"ssm:DescribeInstanceInformation"
],
"Resource": ["*"]
}
]
}
MacOS
brew tap aws/tap
brew install aws-sessionmanager-plugin
Ubuntu / Debian
# package download
curl "https://s3.amazonaws.com/session-manager-downloads/plugin/latest/ubuntu_64bit/session-manager-plugin.deb" \
-o "session-manager-plugin.deb"
# install
sudo dpkg -i session-manager-plugin.deb
# check the version
session-manager-plugin --version
CentOS / Amazon Linux
sudo yum install -y https://s3.amazonaws.com/session-manager-downloads/plugin/latest/linux_64bit/session-manager-plugin.rpm
session-manager-plugin --version
Access command
- instance tag is required to run following command
aws ssm start-session \
--target $(aws ec2 describe-instances \
--filters "Name=tag:Name,Values=${EC2_NAME}" \
"Name=instance-state-name,Values=running" \
--query "Reservations[0].Instances[0].InstanceId" \
--output text \
--region ap-northeast-2) \
--document-name AWS-StartPortForwardingSessionToRemoteHost \
--parameters '{
"host":["${DB_ADDRESS}"],
"portNumber":["${DB_PORT}"],
"localPortNumber":["${DESIRE_LOCAL_PORT}"]
}' \
--region ap-northeast-2
- without tag version
aws ssm start-session --target i-01a195587b7b7c266 --document-name AWS-StartPortForwardingSessionToRemoteHost --parameters '{
"host":["${DB_ADDRESS}"],
"portNumber":["${DB_PORT}"],
"localPortNumber":["${DESIRE_LOCAL_PORT}"]
}' --region ap-northeast-2
The terminal should appear as following screenshot once the connection is successfully established.

Example
- DocDB
mongodb://${DB_USER}:${DB_PASSWORD}@localhost:${DESIRE_LOCAL_PORT}/admin?tlsAllowInvalidHostnames=true&directConnection=true
반응형