Where to store sensitive data in public rails app?

TLDR: Use environment variables!

I think @Bryce’s comment offers an answer, which I’ll just flush out. It seems one approach Heroku recommends is to use environment variables to store sensitive information (API key strings, database passwords). So survey your code and see in which you have sensitive data. Then create environment variables (in your .bashrc file for example) that store the sensivite data values. For example for your database:

export MYAPP_DEV_DB_DATABASE=myapp_dev
export MYAPP_DEV_DB_USER=username
export MYAPP_DEV_DB_PW=secret

Now, in your local box, you just refer to the environment variables whenever you need the sensitive data. For example in database.yml :

development:
  adapter: mysql2
  encoding: utf8
  reconnect: false
  database: <%= ENV["MYAPP_DEV_DB_DATABASE"] %>
  pool: 5
  username: <%= ENV["MYAPP_DEV_DB_USER"] %>
  password: <%= ENV["MYAPP_DEV_DB_PW"] %>
  socket: /var/run/mysqld/mysqld.sock

I think database.yml gets parsed just at the app’s initialization or restart so this shouldn’t impact performance. So this would solve it for your local development and for making your repository public. Stripped of sensitive data, you can now use the same repository for the public as you do privately. It also solves the problem if you are on a VPS. Just ssh to it and set up the environment variables on your production host as you did in your development box.

Meanwhile, if your production setup involves a hands off deployment where you can’t ssh to the production server, like Heroku’s does, you need to look at how to remotely set up environment variables. For Heroku this is done with heroku config:add. So, per the same article, if you had S3 integrated into your app and you had the sensitive data coming in from the environment variables:

AWS::S3::Base.establish_connection!(
  :access_key_id     => ENV['S3_KEY'],
  :secret_access_key => ENV['S3_SECRET']
)

Just have Heroku create environment variables for it:

heroku config:add S3_KEY=8N022N81 S3_SECRET=9s83159d3+583493190

Another pro of this solution is that it’s language neutral, not just Rails. Works for any app since they can all acquire the environment variables.

Leave a Comment