Search code examples
ruby-on-railsdeploymentruby-on-rails-4

Missing production secret_key_base in rails


I have recently deployed an app and got an 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?

Solution

  • For local development Generate a secret using rails secret

    Method #1: Store this secret in your .bashrc or .zshrc

    see https://apple.stackexchange.com/questions/356441/how-to-add-permanent-environment-variable-in-zsh for

    Method #2: Use the dotenv Gem

    Once you have this gem installed, you then create a .env file in the root of your Rails app that does NOT get checked-into the source control.

    https://github.com/bkeepers/dotenv

    Method #3 (if using rhc Openshift client)

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

    For the server Method #1: Heroku

    Option 1: Store the SECRET_KEY_BASE directly onto the environment heroku config:set SECRET_KEY_BASE=xxxx

    Option 2: Store the secret encrypted with the app and use the master.key file to decrypt it.

    Method #2: For AWS, use AWS Secret Manager to store the master key.

    Method #3: For RHC Openshift

    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