Search code examples
grailspasswordsdatasource

Configuring grails datasources with username and password from OS environment


I am currently working on a grails application. Previously I have been using Django alot to create webapps. In django you can easily create settings that are collected from the OS environment. I find that to be an easy solution for making sure that you don't check in usernames and passwords into the source code repository.

So what I would like to do is in the DataSource.groovy be able to lift in the username and password from the OS environment. Has anyone done anything like this, or is this not the way to go forward?

If this is not the "grails way", how is it supposed to be done, because having the username and password in the repository just feels wrong?


Solution

  • You can write code in DataSource.groovy and Config.groovy to get env variable and then set username password and other things. I always to it for my production app, sample code is as follows //Eample is based on url structure like "mysql://username:password@host/database?autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8"

    dataSource {
                String mysqlUrl = System.getenv("DATABASE_URL")
                println ">>>>>> Got DATABASE_URL: ${mysqlUrl} <<<<<<<"
    
                URI dbUri = new URI(mysqlUrl);
                username = dbUri.userInfo.split(":")[0]
                password = dbUri.userInfo.split(":")[1]
    
                String databaseUrl = "jdbc:${dbUri.scheme}://${dbUri.host}${dbUri.path}"
                if (dbUri.port > 0) {
                    databaseUrl += ":${dbUri.port}"
                }
    
                String query = dbUri.query ?: "reconnect=true"
                query += "&autoReconnect=true&useUnicode=yes&characterEncoding=UTF-8"
                databaseUrl += "?${query}"
                url = databaseUrl
                dialect = 'org.hibernate.dialect.MySQL5InnoDBDialect'
            }
    

    This is one of the way I am sure there must be some simpler way to do this.

    PS: I find it simple though :)