问题
Using typesafe config, how do I override the reference configuration with an environment variable? For example, lets say I have the following configuration:
foo: "bar"
I want it to be overriden with the environment variable FOO
if one exists.
回答1:
If I correctly understood your question, the answer is here. You can do
foo: "bar"
foo: ${?FOO}
回答2:
The official doc now describes it very clearly and supports multiple options for this. Here is a brief summary...
Most common way is to use this form:
basedir = "/whatever/whatever"
basedir = ${?FORCED_BASEDIR}
If env variable is set, then it will override your default value, otherwise it will be left intact.
A more convenient way is to use JVM property -Dconfig.override_with_env_vars=true
to override any config variable. In this case you don't have to create duplicate declarations. You env variables will have to be named with prefix CONFIG_FORCE_
. See how env var to config name mapping works in the docs. As an example: CONFIG_FORCE_a_b__c___d
will be mapped to a.b-c_d
.
Finally, if you want to roll out your own mapping, which is similar to the option described above without using override_with_env_vars
you can use some shell hacking as described below.
If you have to use environment variables and if their naming is consistent with config names you can use a bash script like this to automatically convert from your environment vars to JVM cmd args. These -D
JVM args will override Typesafe Config values. Example:
# export my_PROP1=1
# export my_PROP2=2
#
# props=$(env | grep my_ | awk '{print "-D"$_}' ORS=' ')
#
# echo "JVM executable command is: java $props some.jar"
JVM executable command is: java -Dmy_PROP2=2 -Dmy_PROP1=1 some.jar
Convert upper to lower case, do substring operations on env vars as you please if they don't directly map to your config values.
回答3:
I am using the System property -Dconfig.override_with_env_vars=true
. With it all properties are automatically overridden via environment variables.
来源:https://stackoverflow.com/questions/38197406/overriding-configuration-with-environment-variables-in-typesafe-config