ParsaLabs | Blog

A publication about the web and more.

Rails Secrets

| Comments

Often times, developers need to store config values (such as access keys for external APIs) during development. But Rails 4 ships with a built-in secrets.yml file, which you can use to conveniently manage such config vars for development, test and production environments.

Here is an example secrets.yml file (from one of my own apps):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
development:
  secret_key_base: 4a7c0c0a1478943ccd5042a4asdadee8cb957ec2c24cc672509af3c09385b39aeda828691a65asdsadsadas
  s3_access_key_id: <%= ENV["S3_ACCESS_KEY_ID"] %>
  s3_secret_access_key: <%= ENV["S3_SECRET_ACCESS_KEY"] %>
  s3_bucket_name: <%= ENV["S3_BUCKET_NAME"] %>

test:
  secret_key_base: 02f6b64f39cdc6b0242fef06b88asdasdsad686d2b1a59536320504d2b870e457f53230e9asdasdasdasb6c4cfe612187asda270c

# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
  s3_access_key_id: <%= ENV["S3_ACCESS_KEY_ID"] %>
  s3_secret_access_key: <%= ENV["S3_SECRET_ACCESS_KEY"] %>
  s3_bucket_name: <%= ENV["S3_BUCKET_NAME"] %>

As you see, I am storing my Amazon S3 credentials here. Later on, I access these secrets in an initializer:

1
2
3
4
AWS.config(access_key_id:     Rails.application.secrets.s3_access_key_id,
           secret_access_key: Rails.application.secrets.s3_secret_access_key)

S3_BUCKET = AWS::S3.new.buckets[Rails.application.secrets.s3_bucket_name]

To set the ENV variables in Mac Os X, you need to edit the .bash_profile like so:

1
2
3
export S3_ACCESS_KEY_ID="...."
export S3_SECRET_ACCESS_KEY="..."
export S3_BUCKET_NAME="..."

Replacing the dots, with the actual values.

One final tip: to generate new keys for your development and test sections, use the rake secret in terminal.

And that’s it, now you have an easy way to manage your application secrets.

Enjoy & as always don’t forget to provide us with your valuable feedback. Cheers.

Comments