Environment Variables in Elixir

Environment variables are a universal mechanism for conveying configuration information to Unix programs. Let’s look at how to set, get, and list environment variables in Elixir.

# To set a key/value pair, use System.put_env/2. To get a
# value for a key, use System.get_env/1. This will return
# nil if the key isn't present in the environment.

System.put_env("FOO", "1")
IO.puts("FOO: #{System.get_env("FOO")}")
IO.puts("BAR: #{System.get_env("BAR")}")

# Use System.get_env/0 to list all key/value pairs in the
# environment. This returns a map. Here we print all the keys.

IO.puts("")
System.get_env()
|> Map.keys()
|> Enum.each(&IO.puts/1)

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is nil.

$ elixir environment_variables.exs
FOO: 1
BAR: 

TERM_PROGRAM
PATH
SHELL
...
FOO

The list of keys in the environment will depend on your particular machine.

If we set BAR in the environment first, the running program picks that value up.

$ BAR=2 elixir environment_variables.exs
FOO: 1
BAR: 2
...

In Elixir, environment variables are accessed through the System module. The System.put_env/2 function is used to set environment variables, while System.get_env/1 is used to retrieve them. If a variable doesn’t exist, System.get_env/1 returns nil instead of an empty string.

To list all environment variables, we use System.get_env/0 which returns a map. We then use Map.keys/1 to get all the keys and Enum.each/2 to print each one.

This example demonstrates how to interact with environment variables in Elixir, which is a common task in configuration management and system interaction.