Skip to main content
Version: 2.x

How to Read Lists and Maps From Environment Variables

Environment variables, system properties and plain maps are flat: every value is a string under a single name. This guide shows how to read lists, lists of objects and maps from such a flat source.

Goalโ€‹

Read this configuration from environment variables only:

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

final case class Upstream(host: String, port: Int)

final case class Gateway(
allowedOrigins: List[String],
upstreams: List[Upstream],
limits: Map[String, Int]
)

val gateway: Config[Gateway] = deriveConfig[Gateway].mapKey(key => toSnakeCase(key).toUpperCase)

def load[A](config: Config[A], provider: ConfigProvider): Either[Config.Error, A] =
Unsafe.unsafe { implicit unsafe =>
Runtime.default.unsafe.run(provider.load(config).either).getOrThrow()
}

Config#mapKey turns the field names into upper snake case: allowedOrigins is read from ALLOWED_ORIGINS. Each step below uses ConfigProvider.fromMap with the same delimiters as ConfigProvider.envProvider (_ between path segments), so that the example runs anywhere. With the real environment, use ConfigProvider.envProvider with the same variables; it upper-cases the keys it looks up, so the upper-case description is not strictly needed there.

Step 1: Read a List of Strings From One Variableโ€‹

ZIO's flat providers split a value on commas when it is read as a list. One variable holds the whole list:

val origins = ConfigProvider.fromMap(Map("ALLOWED_ORIGINS" -> "https://a.example,https://b.example"), pathDelim = "_")

Reading it as a list splits the value:

load(Config.listOf("ALLOWED_ORIGINS", Config.string), origins)
// res1: Either[Config.Error, List[String]] = Right(
// value = List("https://a.example", "https://b.example")
// )

To use another separator, pass seqDelim, as in ConfigProvider.fromEnv(seqDelim = ";").

Step 2: Read a List of Objects With Indexed Namesโ€‹

A list of objects needs one variable per field per element. Put the index in square brackets after the list's name, then the field: UPSTREAMS[0]_HOST, UPSTREAMS[0]_PORT, and so on:

val upstreams = ConfigProvider.fromMap(
Map(
"UPSTREAMS[0]_HOST" -> "a.internal",
"UPSTREAMS[0]_PORT" -> "8080",
"UPSTREAMS[1]_HOST" -> "b.internal",
"UPSTREAMS[1]_PORT" -> "8081"
),
pathDelim = "_"
)

Each index becomes one element of the list:

load(Config.listOf("UPSTREAMS", deriveConfig[Upstream].mapKey(_.toUpperCase)), upstreams)
// res2: Either[Config.Error, List[Upstream]] = Right(
// value = List(
// Upstream(host = "a.internal", port = 8080),
// Upstream(host = "b.internal", port = 8081)
// )
// )

Most shells can't export a variable with [ in its name, but container platforms and process managers, such as Docker and Kubernetes, can set it.

Step 3: Read a Mapโ€‹

Config.table, or a Map[String, A] field, reads every variable under a prefix. The part of the name after the prefix becomes the key of the map:

val limits = ConfigProvider.fromMap(Map("LIMITS_free" -> "10", "LIMITS_pro" -> "1000"), pathDelim = "_")

Every variable under LIMITS becomes a map entry:

load(Config.table("LIMITS", Config.int), limits)
// res3: Either[Config.Error, Map[String, Int]] = Right(
// value = Map("free" -> 10, "pro" -> 1000)
// )

A map provider keeps the case of the map keys. The environment provider upper-cases every name it reads, so with real environment variables the keys arrive as FREE and PRO. Because _ separates path segments, a map key can't contain _.

Step 4: Put It Togetherโ€‹

All the variables together load the whole Gateway:

val environment = ConfigProvider.fromMap(
Map(
"ALLOWED_ORIGINS" -> "https://a.example,https://b.example",
"UPSTREAMS[0]_HOST" -> "a.internal",
"UPSTREAMS[0]_PORT" -> "8080",
"LIMITS_free" -> "10",
"LIMITS_pro" -> "1000"
),
pathDelim = "_"
)

Loading the whole description:

load(gateway, environment)
// res4: Either[Config.Error, Gateway] = Right(
// value = Gateway(
// allowedOrigins = List("https://a.example", "https://b.example"),
// upstreams = List(Upstream(host = "a.internal", port = 8080)),
// limits = Map("free" -> 10, "pro" -> 1000)
// )
// )

Notesโ€‹

  • A comma inside a value splits it only when the key is read as a list. If a list value can contain commas, choose another delimiter with seqDelim.
  • Structured formats such as HOCON, YAML and TOML have real lists and don't need these conventions. Their providers don't split on commas unless you pass enableCommaSeparatedValueAsList = true. See Config providers.
  • ZIO core providers describes the environment provider and its delimiters.

ZIO Chat

Hi, fellow coder! ๐ŸŒŸ Welcome to your ZIO adventure with the ZIO Chat Bot. ๐Ÿš€ Let's master functional Scala together. From referential transparency to concurrent prowess, I've got your back. Ready to dive in? Your questions, my insights โ€“ let's conquer ZIO! ๐Ÿ’ก๐Ÿค–