@@ -68,6 +68,10 @@ module "subnets" {
6868
6969### Connecting to your new SSM Agent
7070
71+ Prereqs:
72+
73+ - Your IAM users/role needs: ` ssm:StartSession ` , ` ec2:DescribeInstances `
74+
7175``` bash
7276INSTANCE_ID=$( aws autoscaling describe-auto-scaling-instances | jq --raw-output " .AutoScalingInstances | .[0] | .InstanceId" )
7377aws ssm start-session --target $INSTANCE_ID
7781
7882Use [ the awesome ` gossm ` project] ( https://github.com/gjbae1212/gossm ) .
7983
84+ ### Set up port forwarding through your SSM Agent
85+
86+ For example, set up port forwarding on ` localhost ` to connect to an RDS Postgres instance on private subnets that is not publicly accessible.
87+
88+ Prereqs:
89+
90+ - Your IAM user/role needs the following permissions: ` ssm:StartSession ` , ` ec2:DescribeInstances ` , ` rds:DescribeDBInstances `
91+ - Ensure the network architecture and Security Group permissions allow inbound traffic from the SSM Agent EC2 host.
92+
93+ ``` bash
94+ REGION=us-east-1
95+ # Partial match for RDS instance name (e.g., "polygon" matches "acme-prod-polygon-data")
96+ DB_INSTANCE_SUBSTRING=" polygon"
97+ LOCAL_PORT=15432
98+
99+ # 1) Find the running SSM gateway instance ID by tag
100+ INSTANCE_ID=" $(
101+ aws ec2 describe-instances \
102+ --filters " Name=tag:Name,Values=*ssm*" " Name=instance-state-name,Values=running" \
103+ --query ' Reservations[*].Instances[*].InstanceId' \
104+ --region ${AWS_REGION} \
105+ --output text) "
106+
107+ # 2) Find the RDS instance endpoint
108+ RDS_ENDPOINT=" $(
109+ aws rds describe-db-instances \
110+ --region ${AWS_REGION} \
111+ --query " DBInstances[?contains(DBInstanceIdentifier, '${DB_INSTANCE_SUBSTRING} ')].Endpoint.Address | [0]" \
112+ --output text) "
113+
114+ # 3) Dynamically get the RDS port
115+ RDS_PORT=" $(
116+ aws rds describe-db-instances \
117+ --region ${AWS_REGION} \
118+ --query " DBInstances[?contains(DBInstanceIdentifier, '${DB_INSTANCE_SUBSTRING} ')].Endpoint.Port | [0]" \
119+ --output text) "
120+
121+ echo " EC2 Instance ID: $INSTANCE_ID "
122+ echo " RDS Endpoint: $RDS_ENDPOINT "
123+ echo " Setting up port forwarding (ec2) ${RDS_PORT} -> (localhost) ${LOCAL_PORT} "
124+
125+ # 4) Start the port forwarding session
126+ aws ssm start-session \
127+ --target $INSTANCE_ID \
128+ --document-name AWS-StartPortForwardingSessionToRemoteHost \
129+ --parameters " {\" host\" :[\" $RDS_ENDPOINT \" ],\" portNumber\" :[\" $RDS_PORT \" ],\" localPortNumber\" :[\" $LOCAL_PORT \" ]}"
130+ ```
131+
80132<!-- prettier-ignore-start -->
81133<!-- markdownlint-disable -->
82134<!-- BEGINNING OF PRE-COMMIT-TERRAFORM DOCS HOOK -->
0 commit comments