EnvGuard

EnvGuard is a library that makes it easier to write runtime.exs files that take in parameters
from the environment, because everyone keeps insisting on using environment variables.
EnvGuard has three ways of imposing constraints on your environment variables.
- Presence checks allow you to define that a given variable is required or optional.
- Type checks ensure that the value of the environment variable is correct and can be automatically casted.
- Implication constraints allow you to define rules such as "if A is defined, B."
- Cardinality constraints allow you to define rules such as "either A or B must be defined, not both."
Type Checks
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.
Implication Constraints
Implication constraints allow you to make sure that if a variable is defined, a set of other variables must also be defined.
import Config
EnvGuard.constrain(
requires: {"SMTP_HOST", ["SMTP_USERNAME", "SMTP_PASSWORD"]}
)
smtp_host = EnvGuard.optional("SMTP_HOST", :string, nil)
if smtp_host do
config :my_app, :mail,
protocol: :smtp,
host: EnvGuard.required("SMTP_HOST", :string),
port: EnvGuard.optional("SMTP_PORT", :integer, 587),
username: EnvGuard.optional("SMTP_USERNAME", :string),
password: EnvGuard.optional("SMTP_PASSWORD", :string)
else
config :my_app, :mail, []
end
Cardinality Checks
Cardinality checks allow you to define that within a set of variables, either all of them are set, at most one is set, at least one is set, or all or none are set.
import Config
EnvGuard.constrain(
exactly_one: ["DATABASE_URL", "DB_HOST"],
all_or_none: ["DB_HOST", "DB_USER", "DB_PASSWORD"],
at_least_one: ["GITHUB_CLIENT_ID", "GOOGLE_CLIENT_ID"],
at_most_one: ["SENTRY_DSN", "HONEYBADGER_API_KEY"]
)
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? Strings are trimmed before getting length. |
{:max_length, n} |
:string |
Maximum length of the string. Strings are trimmed before getting length. |
{:min_length, n} |
:string |
Minimal length of the string. Strings are trimmed before getting length. |
{:trim, boolean()} |
:string |
Remove leading and trailing whitespace from the value. |