33
votes

I have recently deployed an app and got internal server error because of missing production secret_key_base. After hours of testing, I managed to solve this problem with two methods:

Method 1:

I generated a new secret_key with rake secret and replaced it with <%= ENV["SECRET_KEY_BASE"] %> in secrets.yml. Deployed the app again and this time it worked. But I think that this method is wrong.

Method 2:

I generated a new secret_key with rake secret and added it to environments/production.rb like config.secret_key_base = 'd1f4810e662acf46a33960e3aa5bd0************************, without changing secrets.yml (default is production: <%= ENV["SECRET_KEY_BASE"] %>). Deployed the app again and it works fine.

My questions:

  1. Which method is the best?
  2. If the 2nd method is correct, why rails does not generate a secret_key_base in production.rb by default?
  3. Is there any other method to do that?
4
Method 2 is still working in my server. Yet I need to run bundle exec rake secret command instead rake secret to get appropriate secret key. - zmd94

4 Answers

31
votes

I have finally found the corrent method. None of the methods mentioned in question are the correct one.

Correct method:

We ourselves should generate a secret key (by rake secret) then create an environment variables for SECRET_KEY_BASE by running following command from command prompt:

rhc set-env SECRET_KEY_BASE=3dc8b0885b3043c0e38aa2e1dc64******************** -a myapp

after running this command, connect to your server via SSH and run env so you should see your SECRET_KEY_BASE in the list.

Now restart you app rhc app-stop myapp and rhc app-start myapp, then you are good to go.

6
votes

If you're on a normal Ubuntu machine just put export SECRET_KEY_BASE=" <<< output from rake secret here >>> " in your ~/.bashrc.

Run source ~/.bashrc and restart the app.

3
votes

There is another option that should be a little more secure and that is to add it to the Apache/Nginx configuration file. I'm using Apache and have just used:

SetEnv SECRET_KEY_BASE my_secret

Then just leave the secrets.yml file set to:

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

For a production web server I'm not sure it's valid to assume that a .bashrc file is run and will get your ENV variable set, but I think this way is certain to set it. I'm not and expert so ready to have any risks or reasons why it's not a good idea pointed out to me.

0
votes

Method 1 is correct. You don't want to store your secrets in the code.