Dotenv Rails: Managing Environments Variables in Ruby on Rails

Dotenv Rails Blog Banner

What Is the Dotenv Gem? 

The Dotenv gem is a Ruby library designed to load environment variables from a .env file into the ENV hash, making it easier to manage application configuration. It simplifies the process of configuring applications across different development, testing, and production environments by allowing developers to store configuration in the environment-specific file rather than hard-coding sensitive information within the application itself.

By using the Dotenv gem, developers can enhance security and maintainability of their applications. It enables them to keep environment-specific settings such as database passwords, API keys, and other sensitive data out of source code repositories.

Why Use Dotev with Rails? 

Using the Dotenv gem with Rails provides several benefits that enhance application configuration and security. Here are some key reasons to use Dotenv with Rails:

  • Simplified configuration management: Dotenv allows you to manage environment variables in a straightforward .env file. This eliminates the need to hard-code configuration settings in your application code, making it easier to manage different settings for development, testing, and production environments.
  • Environment-specific settings: Dotenv supports multiple .env files for different environments (e.g., .env.development, .env.test, .env.production). This allows you to maintain separate configurations for each environment, ensuring that your application behaves consistently across development, testing, and production.
  • Improved security: By storing sensitive information like API keys, database passwords, and other credentials in a .env file, you keep these details out of your source code repository. This reduces the risk of exposing sensitive data, especially when using version control systems like Git.
  • Enhanced development workflow: Dotenv automatically loads environment variables when the Rails application starts, which streamlines the setup process. Developers can easily share .env.example files to outline required environment variables.
  • Test environment isolation: In Rails applications, Dotenv ensures that environment variables are reset between tests. This isolation prevents test pollution and makes tests more reliable by ensuring they do not interfere with each other.

Dotnev Gem Features 

The Dotenv gem offers several key features that enhance its utility in application development:

  • Automatic loading: Automatically loads environment variables from a .env file when the application starts. This simplifies the setup process, ensuring that all necessary variables are available without manual intervention.
  • Multi-file support: Supports loading multiple .env files, allowing developers to manage different configurations for various environments. For example, you can have .env.development, .env.test, and .env.production files, each containing environment-specific variables.
  • Command substitution and variable referencing: Allows the use of command substitution and variable referencing within .env files. This means you can dynamically set environment variables based on the output of a command or the value of another variable.
  • Autorestore in tests: In Rails applications, Dotenv automatically restores environment variables after each test, preventing state leakage between tests. This feature can be disabled if needed.
  • Integration with Rake and CLI: Dotenv can be integrated with Rake tasks and used via the CLI to load environment variables before running scripts, providing flexibility in various workflows.
  • Template generation: Generates template files from existing .env files. This is useful for creating example configuration files that can be shared without exposing sensitive information.

Setting Up Dotenv in Rails Using Dotenv Gem

To set up the Dotenv gem in a Rails application, follow these steps:

1. Install the Dotenv Gem: Add the Dotenv gem to your Gemfile in the development and test groups to ensure it is only loaded in these environments:

gem 'dotenv', groups: [:development, :test]

Then, run bundle install to install the gem.

2. Create a .env File: In the root directory of your Rails project, create a .env file and add your environment-specific configuration variables. For example:

S3_BUCKET=YOURS3BUCKET
SECRET_KEY=YOURSECRETKEYGOESHERE

3. Load Environment Variables: Dotenv will automatically load the environment variables from your .env file when the Rails application starts. You can access these variables using the ENV hash:

config.fog_directory = ENV['S3_BUCKET']

4. Customizing Rails Integration: By default, Dotenv loads specific files depending on the RAILS_ENV. These files include .env, .env.development, .env.test, and .env.production. The precedence is as follows:

  • .env.development.local (highest precedence for development)
  • .env.test.local (highest precedence for test)
  • .env.production.local (highest precedence for production)
  • .env.local (common local overrides)
  • .env.development, .env.test, .env.production (environment-specific variables)
  • .env (shared across all environments)

You can customize which files are loaded and their order by modifying the config/application.rb file. For example, to load .env.local in the test environment:

# config/application.rb
Bundler.require(*Rails.groups)

# Load .env.local in test
Dotenv::Rails.files.unshift('.env.local') if ENV['RAILS_ENV'] == 'test'

module YourApp
  class Application < Rails::Application
    # ...
  end
end

5. Rake Tasks Integration: To ensure environment variables are loaded in Rake tasks, require the Dotenv tasks in your Rakefile:

require 'dotenv/tasks'

task mytask: :dotenv do
  # tasks that require environment variables
end

6. Command Line Interface (CLI) Usage: You can use the dotenv executable to load environment variables before running a script:

$ dotenv ./script.rb

To load multiple .env files with precedence, use the -f flag with a comma-separated list of files:

$ dotenv -f ".env.local,.env" ./script.rb

To ignore missing files, add the -i or --ignore flag:

$ dotenv -i -f ".env.local,.env" ./script.rb

By following these steps, you can effectively set up and use the Dotenv gem in your Rails application to manage environment-specific configurations.

Managing and Securely Storing Environment Variables with Configu

Configu is a configuration management platform comprised of two main components, the stand-alone Orchestrator, which is open source, and the Cloud, which is a SaaS solution:

Configu Orchestrator

As applications become more dynamic and distributed in microservices architectures, configurations are getting more fragmented. They are saved as raw text that is spread across multiple stores, databases, files, git repositories, and third-party tools (a typical company will have five to ten different stores).

The Configu Orchestrator, which is open-source software, is a powerful standalone tool designed to address this challenge by providing configuration orchestration along with Configuration-as-Code (CaC) approach.

Configu Cloud

Configu Cloud is the most innovative store purpose-built for configurations, including environment variables, secrets, and feature flags. It is built based on the Configu configuration-as-code (CaC) approach and can model configurations and wrap them with unique layers, providing collaboration capabilities, visibility into configuration workflows, and security and compliance standardization.

Unlike legacy tools, which treat configurations as unstructured data or key-value pairs, Configu is leading the way with a Configuration-as-Code approach. By modeling configurations, they are treated as first-class citizens in the developers' code. This makes our solution more robust and reliable and also enables Configu to provide more capabilities, such as visualization, a testing framework, and security abilities.

Learn more about Configu

Try Configu for free
Painless end-to-end configuration management platform
Get Started for Free