Skip to main content
Version: 2.x

How to Use Environment Variables in a YAML File

A YAML configuration file often needs a few values that differ per machine, such as a port, or that must not be committed, such as a password. The YAML provider can take those values from environment variables while it reads the file, so one file serves every environment.

Goalโ€‹

Write one application.yaml that has defaults for development, takes overrides from the environment, and refuses to start when a required secret is missing.

Step 1: Add the YAML Moduleโ€‹

Add the YAML provider and derivation:

// YAML source (JVM)
libraryDependencies += "dev.zio" %% "zio-config-yaml" % "4.1.3"

// Automatic derivation of config descriptors (JVM)
libraryDependencies += "dev.zio" %% "zio-config-magnolia" % "4.1.3"

Step 2: Write the File With Substitutionsโ€‹

Use ${NAME:-default} for a value with a default, and ${NAME:?message} for a value that must be set. Keep each expression as the whole, unquoted value, and keep defaults and messages to letters, digits and _; the provider leaves anything else as plain text. The YAML reference lists the rules:

server:
host: ${APP_HOST:-localhost}
port: ${APP_PORT:-8080}
database:
url: ${DATABASE_URL:-jdbc_dev_placeholder}
password: ${DATABASE_PASSWORD:?DATABASE_PASSWORD_missing}

A value such as a URL usually contains characters that are not allowed in a default. Give it a placeholder default, as above, or require it with ?.

Step 3: Describe the Settingsโ€‹

Derive the description from case classes that match the file:

import zio._
import zio.config._
import zio.config.magnolia.deriveConfig
import zio.config.yaml._

final case class Server(host: String, port: Int)
final case class Database(url: String, password: Config.Secret)
final case class AppConfig(server: Server, database: Database)

val appConfig: Config[AppConfig] = deriveConfig[AppConfig]

Step 4: Load the File as an Effectโ€‹

Use a ...ZIO constructor, so that a missing file or a missing required variable fails the effect instead of throwing. The substitution happens when the provider is built, so the ? check fails before any key is read:

import java.nio.file.Paths

val loaded: Task[AppConfig] =
for {
provider <- ConfigProvider.fromYamlPathZIO(Paths.get("application.yaml"))
config <- provider.load(appConfig)
} yield config

To use the file for the whole program, build the provider in the bootstrap layer and read the settings with ZIO.config:

import java.nio.file.Paths

object Main extends ZIOAppDefault {
override val bootstrap: ZLayer[ZIOAppArgs, Any, Any] =
ZLayer.fromZIO(ConfigProvider.fromYamlPathZIO(Paths.get("application.yaml"))).flatMap(provider =>
Runtime.setConfigProvider(provider.get)
)

def run = ZIO.config(appConfig).flatMap(config => Console.printLine(s"Listening on ${config.server.port}"))
}

Step 5: Check the Defaultsโ€‹

With none of the variables set, except the required password, the file loads with its defaults. In this check the password is written directly into the YAML text, so the example does not depend on the environment of the machine that runs it:

val yaml: String =
"""
server:
host: ${ZIO_CONFIG_DOCS_UNSET_HOST:-localhost}
port: ${ZIO_CONFIG_DOCS_UNSET_PORT:-8080}
database:
url: ${ZIO_CONFIG_DOCS_UNSET_URL:-jdbc_dev_placeholder}
password: not-a-real-secret
"""
// yaml: String = """
// server:
// host: ${ZIO_CONFIG_DOCS_UNSET_HOST:-localhost}
// port: ${ZIO_CONFIG_DOCS_UNSET_PORT:-8080}
// database:
// url: ${ZIO_CONFIG_DOCS_UNSET_URL:-jdbc_dev_placeholder}
// password: not-a-real-secret
// """

Unsafe.unsafe { implicit unsafe =>
Runtime.default.unsafe.run(ConfigProvider.fromYamlStringZIO(yaml).flatMap(_.load(appConfig))).getOrThrow()
}
// res3: AppConfig = AppConfig(
// server = Server(host = "localhost", port = 8080),
// database = Database(
// url = "jdbc_dev_placeholder",
// password = Secret(<redacted>)
// )
// )

Then run the program with an override, for example APP_PORT=9090 DATABASE_PASSWORD=... sbt run, and check that the port changes. Run it once without DATABASE_PASSWORD and check that it stops with DATABASE_PASSWORD_missing.

Notesโ€‹

ZIO Chat

Hello! ๐Ÿ˜Š I'm your ZIO Chat Bot, designed to be your go-to resource for all things ZIO! Whether you're new to this powerful functional effect system or a seasoned pro, I'm here to assist you. ZIO empowers you to build concurrent and resilient applications in Scala, offering referential transparency, composable data types, type-safety, and more. So, go ahead and ask me anything about ZIO โ€“ I'm here to provide the answers you need! ๐Ÿค–