Logo

Using envvault with Elixir

Note: Please ensure that you have completed the previous steps

Prerequisites

  • Erlang and Elixir installed
  • Mix (Elixir's build tool) installed
  • envvault CLI tool installed
  • An existing Elixir project

Usage

Running Your Application

To run your Elixir application with environment variables from envvault:

$ envvault run --env=dev mix run --no-halt

Caching Environment Variables

For better performance, you can cache your environment variables:

$ envvault run --env=dev -c -- mix run --no-halt

Example Implementation

Here is how to set up a basic Elixir web server with envvault:

# lib/my_app/application.ex
defmodule MyApp.Application do
  use Application

  def start(_type, _args) do
    # Your environment variables are automatically loaded
    port = System.get_env("PORT", "4000") |> String.to_integer()
    db_url = System.get_env("DB_URL")

    children = [
      {Plug.Cowboy, scheme: :http, plug: MyApp.Router, options: [port: port]}
    ]

    opts = [strategy: :one_for_one, name: MyApp.Supervisor]
    Supervisor.start_link(children, opts)
  end
end

# lib/my_app/router.ex
defmodule MyApp.Router do
  use Plug.Router

  plug :match
  plug :dispatch

  get "/" do
    send_resp(conn, 200, "Hello from envvault!")
  end

  match _ do
    send_resp(conn, 404, "Not Found")
  end
end

# mix.exs
defmodule MyApp.MixProject do
  use Mix.Project

  def project do
    [
      app: :my_app,
      version: "0.1.0",
      elixir: "~> 1.12",
      start_permanent: Mix.env() == :prod,
      deps: deps()
    ]
  end

  def application do
    [
      extra_applications: [:logger],
      mod: {MyApp.Application, []}
    ]
  end

  defp deps do
    [
      {:plug_cowboy, "~> 2.0"}
    ]
  end
end