# How to Manage Environment Variables in Rails

*Published on June 02, 2022*

---


Now you might think it’s so easy to access them using the&nbsp;`ENV`&nbsp;hash. Why do we need a different way?

Well, a very common problem when working on multiple Rails applications on the same machine during development is that these applications might have environment variables with the same name. A good example is the database connection string. Different applications will have a different value for the same environment variable.&nbsp;**If you set the environment variable in your shell config file, how can you use different values?**

The same problem will happen in a Continuous Integration (CI) server, where you might have multiple projects running.

So, don’t set the environment variables on the development machines or CI servers. Use the&nbsp;[_dotenv_](https://github.com/bkeepers/dotenv)&nbsp;gem that lets you load variables from a&nbsp;`.env`&nbsp;file into the&nbsp;`ENV`&nbsp;hash when the Rails application loads.

Let’s see how to use this gem.

Add this line to the top of your application’s Gemfile:

```ruby
# A Ruby gem to load environment variables from `.env`.
gem 'dotenv-rails', groups: [:development, :test]
```

Then install the gem using Bundler:

```ruby
$ bundle
```

Add your application configuration to your&nbsp;**\*.env\***&nbsp;file at the root of your project:

```ruby
S3_BUCKET=YOURS3BUCKET
SECRET_KEY=YOURSECRETKEYGOESHERE
```

Whenever your application loads, these variables will be available in ENV:

```ruby
config.fog_directory  = ENV['S3_BUCKET']
```

Don’t forget to add the&nbsp;`.env`&nbsp;file to the&nbsp;`.gitignore`&nbsp;file, so you don’t accidentally push it to GitHub for the whole world to see.

Note: As a hack, you could simply prefix the environment variable with the application name, e.g.&nbsp;`BLOG_S3_BUCKET`, and it will work, but still, it would be nice to have the environment variables nicely scoped within the application and with a concise name.

