Skip to content

Instantly share code, notes, and snippets.

@marinakr
Created October 11, 2021 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marinakr/8a334cafb06d71c730f21392a4360221 to your computer and use it in GitHub Desktop.
Save marinakr/8a334cafb06d71c730f21392a4360221 to your computer and use it in GitHub Desktop.
elixir_vault_config_provider
defmodule HV.ConfigProviders.VaultConfigProvider do
@moduledoc false
@behaviour Config.Provider
require Logger
# Let's pass the path to the JSON file as config
def init(nil), do: "/path/to/vault/token"
def init(path) when is_binary(path), do: path
def load(config, path) do
{:ok, _} = Application.ensure_all_started(:jason)
{:ok, _} = Application.ensure_all_started(:hackney)
{:ok, _} = Application.ensure_all_started(:tesla)
vault_host = System.fetch_env!("VAULT_ADDR")
vault_k8s_role = System.fetch_env!("VAULT_K8S_ROLE")
vault_prefix = System.fetch_env!("VAULT_PREFIX")
vault_env_path = System.get_env("VAULT_ENV_PATH") || "secrets"
{:ok, vault} =
Vault.new(
engine: Vault.Engine.KVV2,
auth: Vault.Auth.Kubernetes,
http: Vault.HTTP.Tesla,
host: vault_host
)
|> Vault.auth(%{role: vault_k8s_role, jwt: File.read!(path)})
{:ok, vault_secrets} = Vault.read(vault, "#{vault_prefix}/#{vault_env_path}")
log_level = String.to_atom(vault_secrets["LOG_LEVEL"] || "error")
Logger.configure(Keyword.merge(config[:logger], level: log_level))
Config.Reader.merge(config,
hello_vault: [
{
HV.Repo,
[
url: fetch_vault_env!(vault_secrets, "DATABASE_URL"),
pool_size: vault_secrets["POOL_SIZE"] || 50
]
}
]
)
end
defp fetch_vault_env!(vault_secrets, secret_key) do
case vault_secrets[secret_key] do
nil ->
IO.puts("Unable to load Vault config secret_key #{secret_key}")
System.halt()
value ->
value
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment