EnvGuard

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
api_key = System.get_env("API_KEY")
user = System.get_env("API_USER")
pass = System.get_env("API_PASS")
auth =
cond do
api_key && user && pass ->
raise "set either API_KEY, or API_USER and API_PASS, not both"
api_key ->
%{api_key: %{key: api_key}, login: nil}
user && pass ->
%{api_key: nil, login: %{user: user, pass: pass}}
true ->
raise "set either API_KEY, or API_USER and API_PASS"
end
config :my_app, MyApp.Client, auth: authend
After
import Config
import EnvGuard
api_key =
group()
|> has(:key, "API_KEY", :string, min_length: 32, format: ~r/^[a-f0-9]+$/)
login =
group()
|> has(:user, "API_USER", :string, max_length: 64)
|> has(:pass, "API_PASS", :string, min_length: 12)
auth =
group()
|> choice(api_key: api_key, login: login)
|> read!()
if auth.api_key do
config :my_app, MyApp.Client,
auth: auth.api_key.key
end
if auth.login do
config :my_app, MyApp.Client,
username: auth.login.user,
password: auth.login.pass
end
If none of the environment variables are set, you'll see a similar error.
** (EnvGuard.ReadError) Invalid environment:
* none of api_key, login is configured
api_key:
* API_KEY is not set
login:
* API_USER is not set
* API_PASS is not set
Or, when you provide both options, you'll see the following.
** (EnvGuard.ReadError) Invalid environment:
* only one group may be configured, but several are: api_key, login
If you set both, but the variables do not meet their constraints.
** (EnvGuard.ReadError) Invalid environment:
* none of api_key, login is configured
api_key:
* API_KEY does not meet the constraint format: ~r/^[a-f0-9]+$/
login:
* API_USER is not set
* API_PASS is not set
Installation
The package can be installed by adding env_guard to your list of
dependencies in mix.exs:
def deps do
[
{:env_guard, "~> 3.0.0-rc.2"}
]
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 of at most 255 characters | atom() |
:charlist |
any value | charlist() |
:integer |
any integral value that's completely parsable as an integer using &Integer.parse/1 |
integer() |
:float |
any value that's completely 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 this table, except a list. Values cannot contain commas because that is the separator. | [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. |
Note: constraints cannot be put on the elements of a list type, they only apply to the list itself.
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.
-
The constraints will be applied to the output of the preprocessors.
System.put_env("NAME", " abcde ") EnvGuard.required("NAME", :string, min_length: 5, preprocess: &String.trim/1)will yield no error, and fallback.
-
Any value that is not a function of arity 1 will result in a raise.
EnvGuard.optional("NAME", :string, "sandbox", min_length: 5, preprocess: :not_a_function)This is not a valid function, so the call will raise.
** (EnvGuard.SpecError) Invalid spec for NAME: * preprocessor :not_a_function is not a function of one argument -
If the function does not produce a value, the error will be propagated.
EnvGuard.optional("NAME", :string, "sandbox", min_length: 5, preprocess: fn _ -> raise "Failed to do something" end)This function fails, so the error is propagated.
** (EnvGuard.ReadError) Invalid environment: * NAME could not be preprocessed: preprocessor raised: Failed to do something -
If the function does not produce a string value, it will raise an error.
EnvGuard.optional("NAME", :string, "sandbox", min_length: 5, preprocess: fn _ -> 1 end)This function fails, so the error is propagated.
** (EnvGuard.ReadError) Invalid environment: * NAME could not be preprocessed: preprocessor returned 1, expected a string
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, and the variables that are set but do not meet their constraints.
** (EnvGuard.ReadError) Invalid environment:
* SMTP_HOST is not set
* SMTP_PASS is not set
** (EnvGuard.ReadError) Invalid environment:
* SMTP_PASS does not meet the constraint min_length: 8
* SMTP_PORT could not be cast: integer expected, got 'abc'
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, if at least one group is valid.
Otherwise the branch's errors are shown.
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!()
-
If exactly one group is correctly configured, the resulting map will hold the values under the key from the choice expression, and all other keys will be
nil.%{ imap: %{port: 123, user: "rudy", host: "example.com", pass: "supersecret"}, smtp: nil } -
If neither of the groups passes validation, an error is raised signaling what is wrong with each group.
** (RuntimeError) Invalid environment: * none of imap, smtp is configured imap: * Environment variable IMAP_PASS is not set smtp: * Environment variable SMTP_HOST is not set * Environment variable SMTP_PASS is not set -
If multiple groups are correctly configured, this is raised signalling which groups are set.
** (EnvGuard.ReadError) Invalid environment: * only one group may be configured, but several are: imap, smtp