🐾Unlocking access to database in private subnet using AWS SSM🐾
❓Development and testing can be complex, especially when it comes to securely accessing databases launched in private subnets. You are lucky if your company has a client VPN setup, as it allows you to connect to resources in private subnet without any additional setup. But what if it does not?
🤓 Use SSM Session Manager to connect to the database in private subnet. It requires you to launch EC2 instance in the same subnet where your database is hosted and connect to it using SSM.
Here is detailed guide how you can do that:
1️⃣ You should create role and instance profile for your EC2 instance. You need to attach arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore managed policy to the instance role, so SSM agent can be installed automatically. You can do these actions from the AWS console or using the following AWS CLI commands:
# Create role
aws iam create-role --role-name DatabaseTestRole --assume-role-policy-document '{"Version":"2012-10-17","Statement":{"Effect":"Allow","Principal":{"Service": "ec2.amazonaws.com"},"Action":"sts:AssumeRole"}}'
# Attach managed policy to the created role
aws iam attach-role-policy --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore --role-name DatabaseTestRole
# Create instance profile and attach role to it
aws iam create-instance-profile --instance-profile-name DatabaseTest
aws iam add-role-to-instance-profile --instance-profile-name DatabaseTest --role-name DatabaseTestRole
2️⃣ Launch an EC2 instance in the private subnet. I provided an example of AWS CLI command to launch small EC2 under Ubuntu OS, you need to replace SUBNET_ID with your private subnet ID. Also, please be aware that AWS updates AMIs and their IDs, so make sure to use the recent one.
aws ec2 run-instances \
--image-id ami-06dd92ecc74fdfb36 \
--instance-type t2.micro \
--subnet-id <SUBNET_ID> \
--iam-instance-profile Name=DatabaseTest
Note: Allow some time for instance to be launched before running next command.
3️⃣ Run the SSM command to connect to the instance.
aws ssm start-session --target <INSTANCE_ID> \
--document-name AWS-StartPortForwardingSessionToRemoteHost \
--parameters host="<RDS_ENDPOINT>",portNumber="5432",localPortNumber="5432"
4️⃣ Connect to the database using JetBrains built-in database add-on, open-source tools like DBeaver, Aqua Data Studio or any other tool of your preference. Example setup for connection with PyCharm:
🎉Happy testing! Feel free to share your thoughts, experiences or any other approaches you know.
If you like this post, you can share APAWS newsletter with friends: