View Source EnvGuard.Macros (env_guard v1.0.0)

Macros for declaring environment variables in runtime.exs.

Import these into your config to fetch, cast, and validate environment variables in a single expression:

import Config
require EnvGuard.Macros
import EnvGuard.Macros

if config_env() == :prod do
  secret_key_base = required("SECRET_KEY_BASE", :string, min_length: 64)
  phx_server = optional("PHX_SERVER", :boolean, false)
end

See EnvGuard.Types for the supported types and constraints.

Summary

Functions

Fetches an optional environment variable, falling back to default.

Fetches a required environment variable, casting it to type and checking constraints.

Functions

Link to this macro

optional(env_name, type, default, constraints \\ [])

View Source (macro)

Fetches an optional environment variable, falling back to default.

When the variable is set, it is cast to type and checked against constraints, and the cast value is returned. When it is not set — or it is set but fails casting or a constraint — default is returned instead. In the failure cases a warning is logged via Logger before falling back.

Examples

phx_server = optional("PHX_SERVER", :boolean, false)
log_level = optional("LOG_LEVEL", {:enum, ["debug", "info", "warning"]}, "info")
Link to this macro

required(env_name, type, constraints \\ [])

View Source (macro)

Fetches a required environment variable, casting it to type and checking constraints.

Returns the cast value. Raises a RuntimeError if the variable is not set, cannot be cast to type, or violates one of the constraints.

Examples

secret_key_base = required("SECRET_KEY_BASE", :string, min_length: 64)
pool_size = required("POOL_SIZE", :integer, min: 1, max: 100)