Secrets Helper

Hello,

I was using the new feature secrets.yml and I have had one thought that might help improve usage.

Many config files in Rails have separate sections for each environment. However, not all environments use the same settings, meaning not just different values but sometimes also different keys. Usually production has a lot more settings than other environments.

For instance: (mongoid.yml)

development:

sessions:

default:

  database: example_development

  hosts:

    - localhost:27017

production:

sessions:

default:

  database: example_production

  hosts:

username: <%= Rails.application.secrets[:mongo][‘user’] %>

password: <%= Rails.application.secrets[:mongo][‘pwd’] %>

replica_set:

hosts: <%= Rails.application.secrets[:mongo][‘replicas’] %>

    - <%= Rails.application.secrets[:mongo]['host'] %>

``

The code example above will not work as in development env, these values are not set. So in order to avoid any errors you would have to:

development:

sessions:

default:

database: example_development

hosts:

  • localhost:27017

production:

sessions:

default:

database: example_production

hosts:

  • <%= Rails.env.production? && Rails.application.secrets[:mongo][‘host’] %>

username: <%= Rails.env.production? && Rails.application.secrets[:mongo][‘user’] %>

password: <%= Rails.env.production? && Rails.application.secrets[:mongo][‘pwd’] %>

replica_set:

hosts: <%= Rails.env.production? && Rails.application.secrets[:mongo][‘replicas’] %>

``

Needless to say, secrets.yml does not need to have same structure in all environments.

So I’ve written a helper to remedy this situation:

development:

sessions:

default:

database: example_development

hosts:

  • localhost:27017

production:

sessions:

default:

database: example_production

hosts:

  • <%= Secrets[‘mongo.host’, ‘production’] %>

username: <%= Secrets[‘mongo.user’, ‘production’] %>

password: <%= Secrets[‘mongo.pwd’, ‘production’] %>

replica_set:

hosts: <%= Secrets[‘mongo.replicas’, ‘production’] %>

``

With this helper, you can specify ‘production’ only values (or other env), and when in production, if they are not present, it will raise exception. However, if in some other environment, it will fail silently (because they are not needed there anyway)

You can still use all-env keys like:

Secrets[‘secret_key_base’]

``