Web Development

Elixir Environment Variables

Using Environment Variables

Elixir environment variables use System.get_env for config.

Introduction to Environment Variables in Elixir

Environment variables are a critical component in configuring applications, allowing for flexibility and security by externalizing configuration data. In Elixir, environment variables can be accessed using the System.get_env/1 function, which retrieves the value of the specified variable.

Using System.get_env/1

The System.get_env/1 function is a straightforward way to fetch environment variables in Elixir. This function takes a single argument, the name of the environment variable, and returns its value as a string or nil if the variable is not set.

Setting Environment Variables

Environment variables can be set in various ways depending on the operating system and the context in which your Elixir application is running. Here are some common methods:

  • Unix/Linux: Use the export command to set a variable in the terminal session, e.g., export API_KEY='your_api_key'.
  • Windows: Use the set command in the Command Prompt, e.g., set API_KEY=your_api_key.
  • Docker: Use the -e flag with docker run to set variables, e.g., docker run -e API_KEY=your_api_key your_image.

Using Environment Variables in Elixir Projects

Environment variables are often used in Elixir projects to manage configuration for different environments (development, test, production). Using environment variables helps in keeping sensitive information like API keys and database credentials out of your codebase.

Best Practices for Using Environment Variables

Here are some best practices for using environment variables in your Elixir applications:

  • Always provide default values for non-sensitive variables to avoid runtime errors.
  • Use a library like Guardian for securely managing secrets.
  • Keep environment variables organized and documented, possibly in a dedicated .env file for development purposes.

Conclusion

Understanding and effectively utilizing environment variables in Elixir can significantly enhance the flexibility and security of your applications. By leveraging System.get_env/1, you can easily manage configuration across different environments, keeping sensitive information out of your source code.

Next
CORS