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.

Tips From the Expert

In my experience, here are tips that can help you better manage environment variables in Ruby on Rails using the Dotenv gem:

  1. Use different .env formats for sensitive staging environments Staging environments often have data closer to production, so avoid replicating .env.production. Use encrypted .env.staging files, or load them from secure services like AWS Secrets Manager to minimize risks.

  2. Set environment defaults in your application code Provide defaults for non-sensitive environment variables directly in the Rails configuration. This prevents application crashes when .env files are missing or incomplete, especially during onboarding or new developer setups.

  3. Restrict .env usage in production environments While Dotenv is great for development and testing, in production, opt for environment variables managed through your hosting provider or orchestration tools (e.g., Kubernetes secrets). This adds a layer of security and avoids the risks of .env leaks.

  4. Use Dotenv validation gems Integrate gems like dotenv_validator to ensure required environment variables are present before your application starts. This prevents runtime errors due to missing configurations and simplifies debugging in non-production environments.

  5. Combine Dotenv with encrypted credentials in Rails 5.2+ For sensitive production data, prefer Rails’ encrypted credentials (using rails credentials:edit). You can use Dotenv to manage non-critical variables while keeping sensitive keys inside credentials.yml.enc for stronger security.

Ran Cohen photo
Ran Cohen
CTO & Co-Founder. Configu
Before co-founding Configu, Ran was a full stack developer at Testim.io and previously served in an elite cybersecurity unit in the Israeli Defense Forces.

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

Related Content

Top 3 Dotenv PHP Libraries and a Quick Tutorial

Dotenv in React with react-dotenv Library: Basics & Quick Tutorial

Dotenv Webpack: The Basics and a Quick Tutorial

Dotenv Typescript: The Basics and a Quick Tutorial

Using npm dotenv Package to Manage Node.js Environment Variables

Using Py Dotenv (python-dotenv) Package to Manage Env Variables

Managing Environment Variables With dotenv

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