Skip to content

Instantly share code, notes, and snippets.

@mpereira-dev
Last active August 17, 2020 23:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpereira-dev/13e8f4ea26453359d2a2d5eb781b315d to your computer and use it in GitHub Desktop.
Save mpereira-dev/13e8f4ea26453359d2a2d5eb781b315d to your computer and use it in GitHub Desktop.
Extract PostgreSQL Credentials for a Pivotal Cloud Foundry App
# * Extract PostgreSQL credentials from a bound service for use in this PCF app.
# ! Your manfiest file must bind the app to an existing PostgreSQL service via 'services'.
# @env VCAP_SERVICES - The Cloud Foundry services this app is bound to. This is set automatically for you.
# @env POSTGRES_SERVICE - The name of the specific PostgreSQL service to use. This is useful if your app is bound to multiple services.
# @env POSTGRES_SERVICE_KEY - The PostgreSQL service vendor key. Defaults to aws-rds-postgres for AWS.
# ? Reference: https://docs.cloudfoundry.org/devguide/deploy-apps/environment-variable.html#VCAP-SERVICES
function getDBCredentials {
echo "[INFO] Extracting DB credentials from VCAP_SERVICES...";
# Assume it is an AWS RDS PostgreSQL service if not specified.
if [[ $POSTGRES_SERVICE_KEY == "" ]]; then POSTGRES_SERVICE_KEY="aws-rds-postgres"; fi
if [ -z "$POSTGRES_SERVICE" ]; then
echo "[WARN] var POSTGRES_SERVICE is not defined. Did you forget to include it in your vars.yml file?"\
"Attempting to use the first, bound, PostgreSQL service if any.";
CREDENTIALS=$(echo $VCAP_SERVICES | jq .\"${POSTGRES_SERVICE_KEY}\"[0].credentials);
else
echo "[INFO] POSTGRES_SERVICE is set to [ ${POSTGRES_SERVICE} ]. Attempting to extract credentials.";
CREDENTIALS=$(echo $VCAP_SERVICES | jq -c ".\"${POSTGRES_SERVICE_KEY}\"[] | select(.name == \"${POSTGRES_SERVICE}\").credentials")
fi
if [[ -z "$POSTGRES_SERVICE" && -z "$CREDENTIALS" ]]; then
echo "[ERROR] VCAP_SERVICES does not contain any PostgreSQL services."\
"Did you forget to bind the service in your manfiest.yml file?";
exit 2;
elif [ -z "$CREDENTIALS" ]; then
echo "[ERROR] VCAP_SERVICES does not contain the specified POSTGRES_SERVICE named [ ${POSTGRES_SERVICE} ]."\
"Did you forget to bind the service in your manfiest.yml file? Maybe check for typos?";
exit 2;
fi
DB_NAME=$(echo $CREDENTIALS | jq .database)
DB_HOST=$(echo $CREDENTIALS | jq .hostname)
DB_PORT=$(echo $CREDENTIALS | jq .port)
DB_USERNAME=$(echo $CREDENTIALS | jq .username)
DB_PASSWORD=$(echo $CREDENTIALS | jq .password)
DB_URI=$(echo $CREDENTIALS | jq .uri)
echo "[INFO] Sucessfully extracted the DB credentials."
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment