Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@Sch3lp
Copy link

Sch3lp commented Jul 15, 2019

Hi!

Thanks because this gist helped me out, but only after I modified the first part of the script.

I'm not using the More robust way(?) (because you don't seem to know either if it's more robust ;))

Anyway, the things I fixed were:
line 17:

export SPRING_DATASOURCE_URL=$(echo "jdbc:$DB_TYPE://$DB_HOST:$DB_PORT/$DB_DATABASE")

line 19:

export SPRING_DATASOURCE_PASSWORD=$DB_PASSWORD

@wwerner
Copy link
Author

wwerner commented Jul 28, 2019

Thanks @Sch3lp! Updated. I'm using the second way, so I didn't notice. And no, I actually don't know which one is better. The second one has been working for me for one or two years by now, so I'm sticking to that.

@lucascaton
Copy link

lucascaton commented Jan 4, 2020

Very helpful, thanks! 😃

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