Skip to content

Setting env values to Hocon props #1505

Description

@arlengur

Hocon doc says:
By setting the JVM property -Dconfig.override_with_env_vars=true it is possible to override any configuration value using environment variables even if an explicit substitution is not specified.

The environment variable value will override any pre-existing value and also any value provided as Java property.

With this option enabled only environment variables starting with CONFIG_FORCE_ are considered, and the name is mangled as follows:

  • the prefix CONFIG_FORCE_ is stripped
  • single underscore(_) is converted into a dot(.)

Set array values outside configuration files
Setting the value of array items from java properties or environment variables require specifying the index in the array for the value. So, while in HOCON you can set multiple values into an array or append to an array.
Using environment variables you specify the exact position.

My config application.conf:

HttpServerConfig {
  # The port to listen on.
  port = 8080
  port = ${?PORT}

  # The hostname to listen on.
  host = "localhost"
  host = ${?HOST}

  source = ["LEGACY_HISTORICAL", "./src/test/resources/marmot_day_test1.tsv"]
  path = []
}

Here is main class:

import zio._
import zio.config.magnolia._
import zio.config.typesafe.TypesafeConfigProvider

case class HttpServerConfig(
  host: String,
  port: Int,
  sourceFilePath: List[String],
  path: List[String],
)

object HttpServerConfig {
  implicit val config: Config[HttpServerConfig] =
    deriveConfig[HttpServerConfig].nested("HttpServerConfig")
}

object MainA extends ZIOAppDefault {
  override val bootstrap = Runtime.setConfigProvider(TypesafeConfigProvider.fromResourcePath())

  val workflow = ZIO
    .config[HttpServerConfig](HttpServerConfig.config)
    .flatMap { config =>
      Console.printLine(
        "Application started with following configuration:\n" +
          s"\thost: ${config.host}\n" +
          s"\tport: ${config.port}\n" +
          s"\tsource: ${config.source}\n" +
          s"\tpath: ${config.path}"
      )
    }

  def run = workflow
}

And the same code works for TypesafeConfig.
Here is my example https://github.com/arlengur/zio-conf

Just run:
CONFIG_FORCE_HttpServerConfig_path_0=z CONFIG_FORCE_HttpServerConfig_path_1=q sbt run -Dconfig.override_with_env_vars=true
And you will get output from TypesafeConfig and error from ZIO

What's wrong here?!

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions