Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a different config file while running sbt?

Tags:

scala

akka

sbt

When in sbt, is it possible to pass a different config file to use?

sbt run

That will use the default config file application.conf

I want to be able to toggle between different config files during development, how can I pass this as a argument while inside of sbt.

like image 203
Blankman Avatar asked Aug 06 '16 15:08

Blankman


2 Answers

You can use the -D flag to override any specific property you want inside your configuration files. This has been available since version 1.0.1 afaik. Example:

sbt run -D akka.cluster.seed-nodes=["akka.tcp://TestApp@host1:2552", "akka.tcp://TestApp@host2:2552"]

This would replace whatever value application.conf holds for:

akka {
  cluster {
    seed-nodes = ["", "", /// etc]
  }
}

Alternatively, if you want to override the whole config, do something like this:

val runtimeMxBean = ManagementFactory.getRuntimeMXBean
val arguments = runtimeMxBean.getInputArguments.asScala.toList

val config = arguments.find(_.contains("config.path")) match {
  case Some(value) => {
   val opt = value.split("=")
   if (Files.exists(opt.last)) {
     ConfigFactory.load(opt.last)
   } else {
     ConfigFactory.load("application.conf")
   }
  case None => ConfigFactory.load("application.conf")
}
  • Pass the file path do your config file using -D, such as config.path=....
  • When you load the configuration, you need to do something like check if there is a runtime argument provided which specifies the file path, check if the file exists, and load that file instead.

Update: Option 3: Use config.resource

You can override the whole config file with -Dconfig.resource=filepath, if you ever need to load a completely separate one.

Option 4

You can also override specific values of config options with environment variables. It looks like this:

database {
  host = "localhost"
  host = ${?DATABASE_HOST}
}

This means if a DATABASE_HOST env variable is set, its value will be used to override whatever application.conf already holds for that key.

like image 174
flavian Avatar answered Oct 31 '22 10:10

flavian


Also can use -D to add the external resources folder in sbt, example(add into build.sbt, if use module, this should be added into module too):

val myResourceDirectory = Option(System.getProperty("myResourceDirectory")).getOrElse("hello_world")
unmanagedResourceDirectories in Compile += baseDirectory.value / myResourceDirectory

add specific myResourceDirectory into unmanagedResourceDirectories, so the usage maybe like:

sbt -DmyResourceDirectory=myfolder/local //local
sbt -DmyResourceDirectory=myfolder/dev //dev
sbt -DmyResourceDirectory=myfolder/prod //prod
like image 45
chengpohi Avatar answered Oct 31 '22 11:10

chengpohi