Last active
August 13, 2024 13:18
-
-
Save bertrandmartel/6d3b5324a853af2341ae854f5a3fbd5d to your computer and use it in GitHub Desktop.
port forwarding for RDS database via system manager plugin + build credentials in pgpass file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
INSTANCE_NAME="my_instance" | |
DATABASE=database_name | |
RDS_HOST="[DATABASE].[REGION].rds.amazonaws.com" | |
RDS_SECRET="my-secret" # should have username and password properties | |
RDS_PORT=5432 | |
LOCAL_PORT=5433 | |
read username password < <(echo $(aws secretsmanager get-secret-value \ | |
--secret-id $RDS_SECRET | \ | |
jq -r '.SecretString' | \ | |
jq -r '.username, .password')) | |
INSTANCE_ID=$(aws ec2 describe-instances \ | |
--filters 'Name=tag:Name,Values='"$INSTANCE_NAME"'' | \ | |
jq -r '.Reservations[0].Instances[0].InstanceId') | |
touch ~/.pgpass | |
echo "localhost:$LOCAL_PORT:$DATABASE:$username:$password" > ~/.pgpass | |
chmod 0600 ~/.pgpass | |
echo "---------------------------------------------------" | |
echo "psql -h localhost -p $LOCAL_PORT -d $DATABASE -U $username" | |
echo "---------------------------------------------------" | |
aws ssm start-session \ | |
--target $INSTANCE_ID \ | |
--document-name AWS-StartPortForwardingSessionToRemoteHost \ | |
--parameters '{"host":["'"$RDS_HOST"'"],"portNumber":["'"$RDS_PORT"'"], "localPortNumber":["'"$LOCAL_PORT"'"]}' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment