EnvGuard Hex Version Hex Docs

EnvGuard is a library that makes it easier to write runtime.exs files that take in parameters from the environment.

The idea is that EnvGuard allows you to define which environment variables an application needs, what their type is expected to be, and whether they are optional for the application to start.

The api ensures that the values are read from the environment and are cast into their proper Elixir types.

Before

import Config

if config_env() == :prod do
  secret_key_base =
    System.get_env("SECRET_KEY_BASE") ||
      raise """
      environment variable SECRET_KEY_BASE is missing.
      You can generate one by calling: mix phx.gen.secret
      """

  if System.get_env("PHX_SERVER") do
    config :my_app, MyAppWeb.Endpoint, server: true
  end
end

After

import Config

if config_env() == :prod do
  secret_key_base = EnvGuard.required("SECRET_KEY_BASE", :string, min_length: 64)

  phx_server = EnvGuard.optional("PHX_SERVER", :boolean, false)
  config :my_app, MyAppWeb.Endpoint, server: phx_server
end

If the environment variable is not defined, you will see the same error.

** (RuntimeError) Environment variable SECRET_KEY_BASE is not set
    /Users/christophe/Documents/Code/loomy/data-api/config/runtime.exs:5: (file)
    (stdlib 6.2) erl_eval.erl:919: :erl_eval.do_apply/7
    (stdlib 6.2) erl_eval.erl:663: :erl_eval.expr/6
    (stdlib 6.2) erl_eval.erl:271: :erl_eval.exprs/6
    (elixir 1.18.1) lib/code.ex:572: Code.validated_eval_string/3

Or, when the type or constraints are not met, an error explaining whats wrong.

** (RuntimeError) Environment variable SECRET_KEY_BASE does not meet constraints. string is shorter than 64 characters
    /Users/christophe/Documents/Code/loomy/data-api/config/runtime.exs:5: (file)
    (stdlib 6.2) erl_eval.erl:919: :erl_eval.do_apply/7
    (stdlib 6.2) erl_eval.erl:663: :erl_eval.expr/6
    (stdlib 6.2) erl_eval.erl:271: :erl_eval.exprs/6
    (elixir 1.18.1) lib/code.ex:572: Code.validated_eval_string/3

An option variable will use the default value if the set value is not of the correct type.

13:32:57.303 [warning] Environment variable PHX_SERVER is set but not of type :boolean. boolean expected, got '25'. Falling back to default.

Installation

The package can be installed by adding env_guard to your list of dependencies in mix.exs:

def deps do
  [
    {:env_guard, "~> 2.1.0"}
  ]
end

Documentation is available on HexDocs.

Types

EnvGuard supports basic types out of the box, and lists of these types.

Type Values Elixir Type
:boolean true, TRUE, 1, false, FALSE, 0 boolean()
:string any value String.t()
:atom any value atom()
:charlist any value charlist()
:integer any integral value that's parsable as an integer using &Integer.parse/1 integer()
:float any value that's parsable as a float using &Float.parse/1 float()
:ip any IPv4 or IPv6 address parsable using &:inet.parse_strict_address/1 :inet.ip_address()
{:list, type} a comma-separated list of values for any given type in the above table. [type]
{:enum, [binary]} any value that is a member of the values given in the list of the enum type. String.t()

Constraints

Constraint Applicaple types Description
{:length, n} {:list, type} Exact length the list should be.
{:min_length n} {:list, type} Minimal length the list should be.
{:max_length, n} {:list, type} Maximal length the list should be.
{:min, n} :integer Minimal value for the integer.
{:max, n} :integer Maximum value for the integer.
{:allow_empty?, boolean()} :string Is the env value allowed to be empty?
{:max_length, n} :string Maximum length of the string.
{:min_length, n} :string Minimal length of the string.
{:format, Regex.t()} :string The value must match the regex.

Preprocessing

You can add 0 or more preprocessor functions that will be called on the raw environment value before the constraints and casts are executed. A typical use case would be to trim a string, change casing, remove base64 prefixes, etc.

When a preprocessor is used, the function must return a String. If the function does not returna string, the call to either required or optional will fail. So if pre-processing fails in any way, an error is raised. The fallback value is not used.

Groups

Groups allow you to define a set of environment variables with their own constraints (i.e., required/optional) to be checked, and enforce that they must all be valid. This is useful for scenarios where you need multiple environment variables to be set (e.g., IMAP configuration).

The following example requires the host, username, and password to be set in the environment. The port may optionally be set, and defaults to 587.

smtp =
  group()
  |> has(:host, "SMTP_HOST", :string)
  |> has(:user, "SMTP_USER", :string)
  |> has(:pass, "SMTP_PASS", :string, min_length: 8)
  |> may_have(:port, "SMTP_PORT", :integer, 587)
  |> read!()

If the variables have been set, the value of smtp will be a map that has the value for each variable written under it's given key.

%{port: 587, user: "rudy", host: "example.com", pass: "supersecret"}

If some variables are not set, the error will list all the variables that are missing.

** (RuntimeError) Invalid environment:
  * Environment variable SMTP_HOST is not set
  * Environment variable SMTP_PASS is not set

Choice

The groups are useful for defining a single group, but sometimes you also want to have mutually exclusive groups. For example, either a set of environment variables for SMTP or IMAP, but never both.

The choice expression allows you to define exactly this. It accepts 1 or more groups, and will check that exactly one of those groups is correctly configured. Partially configured groups are ignored.

smtp =
  group()
  |> has(:host, "SMTP_HOST", :string)
  |> has(:user, "SMTP_USER", :string)
  |> has(:pass, "SMTP_PASS", :string, min_length: 8)
  |> may_have(:port, "SMTP_PORT", :integer, 587)

imap =
  group()
  |> has(:host, "IMAP_HOST", :string)
  |> has(:user, "IMAP_USER", :string)
  |> has(:pass, "IMAP_PASS", :string, min_length: 8)
  |> may_have(:port, "IMAP_PORT", :integer, 587)

mail =
  group()
  |> choice(imap: imap, smtp: smtp)
  |> read!()