简体   繁体   中英

SBT - How can I add/modify values to application.conf file based on an external source

I read that SBT has functionality to generate source code and resource files .

In my case I want to add/modify a field in an application.conf file during compilation/packaging of the project (leaving the others in place)

For instance my application.conf file has something like:

A {
  B = "Some Value"
  C = "Some value to be modified"
}

I would like in the SBT to read an external file and change or add the value of AB or AC

So if it is possible to do something along the lines of:

build.sbt

lazy val myProject = project.in(file('myproject')
// pseudo code - How do I do this?
.sourceGenerators in Compile += "Read file /path/to/external/file and add or replace the value of application.conf A.B = some external value"

You can replace the values with environment variable values provided while compiling / building your project. For that you'd have to

A {
  B = "Some Value"
  B = ${?B_ENV}
  C = "Some value to be modified"
  C = ${?C_ENV} 
}

Where B_ENV and C_ENV are the environment variables you set in your terminal either before build or within the build command (before it)

$ B_ENV=1 C_ENV=2 sbt run

Source: https://www.playframework.com/documentation/2.6.x/ProductionConfiguration#using-environment-variables

In this case you can do without sbt and this approach would also work with maven or cradle .

The *.conf support orignates from typesafe config ( https://github.com/lightbend/config ).

There is a feature to get environment variables to be used in the configuration which should be a good fit to solve the problem.

There are two approaches I would suggest to use

1.) Fail on missing configuration

If configuration of this vallue is important and to prevent the deplyment of misconfigurated application the startup should fail on missing environment variables.

in application.conf

key=${TEST} // expects "TEST" to be set, fails otherwise

2.) Hardcoded value with override

If there is a sensible default behaviour that only in some circumstances should be changed.

in application.conf

key="test" // hardcoded key
key=${?TEST} // override "key" with 3nv "$TEST" value, when it is given

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM