Last active
December 18, 2018 14:03
-
-
Save relistan/67f7081a99cb98485dd4403fe23d58c4 to your computer and use it in GitHub Desktop.
Elixir Distillery Env Var Provider
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule EnvVar.Provider do | |
use Mix.Releases.Config.Provider | |
require Logger | |
def init(app: app, prefix: prefix, env_map: env_map) do | |
persist(app, prefix, env_map) | |
end | |
# E.g. | |
# %{ | |
# sidecar_addr: %{ | |
# type: :string, | |
# default: "singularity.uw2.prod.sms.community:7777", | |
# }, | |
# foo_count: %{ | |
# type: :integer, | |
# default: "123" | |
# }, | |
# bar: %{ | |
# type: {:list, :integer, ","} | |
# default: "123,123,123" | |
# } | |
# } | |
defp persist(app, prefix, env_map) do | |
for {key, config} <- env_map do | |
if is_nil(Map.get(config, :type, nil)) do | |
Logger.warn("Missing type information in for #{key}") | |
else | |
env_value = | |
lookup_key_for(key, prefix) | |
|> System.get_env() | |
|> set_default(Map.get(config, :default, "")) | |
result = convert(config[:type], env_value) | |
Application.put_env(app, key, result, persistent: true) | |
end | |
end | |
end | |
defp convert(:float, env_value) do | |
{val, _extra} = Float.parse(env_value) | |
val | |
end | |
defp convert(:integer, env_value) do | |
{val, _extra} = Integer.parse(env_value) | |
val | |
end | |
defp convert(:string, env_value) do | |
env_value | |
end | |
defp convert({:list, type, separator}, env_value) do | |
env_value | |
|> String.split(separator) | |
|> Enum.map(fn val -> | |
convert(type, val) | |
end) | |
end | |
defp set_default(value, default) when is_nil(value) do | |
default | |
end | |
defp set_default(value, default) do | |
if String.length(value) < 1 do | |
default | |
else | |
value | |
end | |
end | |
defp lookup_key_for(key, prefix) do | |
key_str = | |
key | |
|> Atom.to_string() | |
|> String.upcase() | |
"#{String.upcase(prefix)}_#{key_str}" | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
release :envoymon do | |
set version: current_version(:envoymon) | |
set applications: [ | |
:runtime_tools | |
] | |
env_config = %{ | |
sidecar_addr: %{ | |
type: :string, | |
default: "singularity.foo.community:7777", | |
}, | |
foo_count: %{ | |
type: :integer, | |
default: "123" | |
} | |
} | |
set config_providers: [ | |
{EnvVar.Provider, [app: :envoymon, prefix: "envoymon", env_map: env_config]} | |
] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment