Skip to content

Instantly share code, notes, and snippets.

@wwerner
Last active April 29, 2021 07:26
Show Gist options
  • Save wwerner/66ee4b1050bd5824dcfd9a5e0cd07f12 to your computer and use it in GitHub Desktop.
Save wwerner/66ee4b1050bd5824dcfd9a5e0cd07f12 to your computer and use it in GitHub Desktop.
Parse Heroku DB URL into Spring Boot Datasource Environment Variables
# Two possibilities to parse a Postgres DB URL from heroku into environment variables
# that Spring Boot understands.
# You would need that, if you do not build on heroku but push docker images
# from another source
# Does not need bash. Works on alpine linux / busybox. Tested with openjdk:8-jdk-alpine base image.
export DATABASE_URL=postgres://user:password@host:port/database
# Naive way, would break with [@:/] in username or password.
DB_TYPE=$(echo $DATABASE_URL | awk -F'[:@/]' '{print $1}')"ql"
DB_USER=$(echo $DATABASE_URL | awk -F'[:@/]' '{print $4}')
DB_PASSWORD=$(echo $DATABASE_URL | awk -F'[:@/]' '{print $5}')
DB_HOST=$(echo $DATABASE_URL | awk -F'[:@/]' '{print $6}')
DB_PORT=$(echo $DATABASE_URL | awk -F'[:@/]' '{print $7}')
DB_DATABASE=$(echo $DATABASE_URL | awk -F'[:@/]' '{print $8}')
export SPRING_DATASOURCE_URL=$(echo "jdbc:$DB_TYPE://$DB_HOST:$DB_PORT/$DB_DATABASE")
export SPRING_DATASOURCE_USERNAME=$DB_USER
export SPRING_DATASOURCE_PASSWORD=$DB_PASSWORD
echo $SPRING_DATASOURCE_URL
# Alternate way, using cut instead of awk.
DB_TYPE=$(echo $DATABASE_URL | cut -d':' -f1)"ql"
DB_TMP=$(echo $DATABASE_URL | cut -d':' -f2- | sed 's/^\/\///')
DB_TMP_USER_PASS=$(echo $DB_TMP | cut -d'@' -f1)
DB_HOST_PORT_DB=$(echo $DB_TMP | cut -d'@' -f2-)
DB_USER=$(echo $DB_TMP_USER_PASS | cut -d':' -f1)
DB_PASS=$(echo $DB_TMP_USER_PASS | cut -d':' -f2)
export SPRING_DATASOURCE_URL=$(echo "jdbc:$DB_TYPE://$DB_HOST_PORT_DB")
export SPRING_DATASOURCE_USERNAME=$DB_USER
export SPRING_DATASOURCE_PASSWORD=$DB_PASS
echo $SPRING_DATASOURCE_URL
echo $SPRING_DATASOURCE_USERNAME
echo $SPRING_DATASOURCE_PASSWORD
@lucascaton
Copy link

Very helpful, thanks! 😃

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment