Neil Neil - 1 month ago 7x
Ruby Question

Where is SECRET_KEY_BASE environment variable located when I start Rails app in Production

In the Rails 4 In Action Book, it states that after doing some other setup: the final setup to boot up your rails app in production mode (with web brick) is to enter this command in terminal:

SECRET_KEY_BASE='rake secret' rails s -e production

I am trying to see where the environment variable of
is stored.

it says that the
variable is an environment variable:

secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

But I looked within
and the variable
is not there.

Ultimately I want to know: where is environment variable and its value? Is it stored somewhere in my rails app? I hope not for security purposes if I push this app to github. I assume it is not stored in the app but in my computer system somewhere. Within a different terminal window I do
but nothing gets returned.

Thanks in advance for helping me understand the missing pieces.

As a side note: I am aware of this question, but the question is not as detailed and there is no provided answer.


When you run this:

SECRET_KEY_BASE='rake secret' rails s -e production

you are not actually 'saving' the secret key for future you. You're defining it on a one-time basis. Whenever you run a Ruby command you can set temporary environment variables:

# from shell
KEY="VAL" OTHER_KEY=OTHER_VAL ruby my_command.rb

# from the ruby script
puts ENV["KEY"] # => "VAL"
puts ENV["OTHER_KEY"] # => "OTHER_VAL"

To persist the environment variables you have a couple options. You could hard code them in your source code, but this is probably not a good idea because if you push your code to Github, anyone will be able to see it. That's kind of the point of environment variables, anyway, that you can keep them system specific.

Option A

You can set them in .bashrc or .bash_profile

First get the result of rake secret (will be a random string) and set a shell variable:

KEY=`rake secret` # uses backticks to get command result

Then add a line in bashrc to export it:

echo -e "export SECRET_KEY_BASE=$KEY" >> ~/.bashrc

Option B

This is the one I'd recommend, you can use dotenv or figaro to manage your environment variables in an app-specific way, i.e. without cluttering up your bashrc.

For example with dotenv you'd create a .env file which contains:

# change this to the result of rake secret  

This would be excluded from source control by adding it to gitignore.

Then in your ruby app you call

require 'dotenv'

and your ENV["SECRET_KEY_BASE"] will be set.

If you want you can make a .env.example file (included in source control) which shows which environment variables need to be defined. Then when the app is cloned you can run mv .env.example .env and customize .env.