Last active
February 5, 2025 14:08
-
-
Save niradler/8693699e310347a224593dd752e1c18b to your computer and use it in GitHub Desktop.
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 | |
# Variables | |
REGION="" # e.g., us-east-1 | |
SECRET_NAME="" # Replace with your secret name | |
USE_IAM_AUTH=false # Set to true if you want to use IAM auth | |
# Function to fetch secret from AWS Secrets Manager | |
fetch_secret() { | |
echo "Fetching secret from AWS Secrets Manager..." | |
SECRET_JSON=$(aws secretsmanager get-secret-value --region "$REGION" --secret-id "$SECRET_NAME" --query 'SecretString' --output text) | |
if [ $? -ne 0 ]; then | |
echo "Error: Unable to fetch secret." | |
exit 1 | |
fi | |
# Extract values from the secret JSON | |
DB_USER=$(echo "$SECRET_JSON" | jq -r '.username') | |
DB_HOST=$(echo "$SECRET_JSON" | jq -r '.cluster_endpoint') | |
DB_PORT=$(echo "$SECRET_JSON" | jq -r '.port') | |
DB_NAME=$(echo "$SECRET_JSON" | jq -r '.database_name') | |
DB_PASS=$(echo "$SECRET_JSON" | jq -r '.password') | |
} | |
# Function to generate IAM DB authentication token | |
generate_iam_token() { | |
echo "Generating IAM authentication token..." | |
IAM_TOKEN=$(aws rds generate-db-auth-token --hostname "$DB_HOST" --port "$DB_PORT" --region "$REGION" --username "$DB_USER") | |
if [ $? -ne 0 ]; then | |
echo "Error: Unable to generate IAM authentication token." | |
exit 1 | |
fi | |
} | |
# Connect to PostgreSQL | |
connect_to_db() { | |
echo "Connecting to PostgreSQL database..." | |
if [ "$USE_IAM_AUTH" = true ]; then | |
generate_iam_token | |
PASSWORD="$IAM_TOKEN" | |
else | |
PASSWORD="$DB_PASS" | |
fi | |
# Uncomment the following line to download the SSL certificate | |
# wget -q https://truststore.pki.rds.amazonaws.com/global/global-bundle.pem | |
PGPASSWORD="$PASSWORD" psql "host=$DB_HOST port=$DB_PORT user=$DB_USER dbname=$DB_NAME sslmode=verify-full sslrootcert=global-bundle.pem" | |
} | |
# Main Execution | |
fetch_secret | |
connect_to_db |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment