Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage application.conf in several environments with play 2.0?

With Play 1.2, I can prefix the configuration keys with the framework ID or application mode as follows:

# Production configuration
%prod.http.port=80
%prod.application.log=INFO
%prod.application.mode=prod

But it doesn't seem to work with 2.0.

Is there any way to make it work?

like image 596
tototoshi Avatar asked Mar 15 '12 15:03

tototoshi


2 Answers

Play 2 doesn't force you to use any particular method to manage your environments. But it provides you with powerful and flexible tools to implement it yourself according to the needs of your project.

For instance a common pattern is keeping common environment settings in one file and having environment-specific overrides in other files. In order to do that you will need a custom Global object (you can put it right into the ./app/Global.scala). The following code is valid as of Play 2.1.1 (Scala 2.10):

import java.io.File
import play.api._
import com.typesafe.config.ConfigFactory

object Global extends GlobalSettings {
  override def onLoadConfig(config: Configuration, path: File, classloader: ClassLoader, mode: Mode.Mode): Configuration = {
    val modeSpecificConfig = config ++ Configuration(ConfigFactory.load(s"application.${mode.toString.toLowerCase}.conf"))
    super.onLoadConfig(modeSpecificConfig, path, classloader, mode)
  }
}

Now you can put application.dev.conf, application.test.conf, and application.prod.conf into your ./conf with environment specific overrides (while keeping common settings in application.conf).

In this sample we're relying on the Play's own mode which usually makes sense, but you can be as granular as you want and use environment variables or whatever you feel like.

See also: Typesafe Config

like image 166
coffeesnake Avatar answered Oct 17 '22 17:10

coffeesnake


I have had this question for a long time as well and below is the best approach I've learned so far, I got a hint when asking a similar question on the Play 2 google group.

In you application.config use the following syntax to override a configuration value when a system parameter is present:

# Local machine fallback URI
mongodb.uri="mongodb://192.168.56.101:27017/application"
# Env variable override
mongodb.uri=${?MONGOLAB_URI}

The question mark means that you don't override with the env variable if it is not set. If you just use ${MONGOLAB_URI} you expect the variable to be set and, I assume, you get an exception of some kind if it is not set.

For completeness, here is an example of how you'd read the value:

lazy val mongoUri = current.configuration.getString("mongodb.uri").getOrElse("mongodb:///")

With this approach there is one caveat: make sure you keep your system param configuration in a SCM of some kind.

like image 13
Magnus Avatar answered Oct 17 '22 19:10

Magnus