ERB in credentials.yml

I’m in the process of migrating a legacy Rails app from plaintext secrets.yml-based configuration to using credentials.yml for static secrets and environment variables for runtime configuration. It seems that the trivial path of basically writing the old secrets.yml file into the new format using rails credentials:edit and replacing references to Rails.application.secrets with Rails.application.credentials in my application is just a fundamentally unworkable strategy, for the simple reason that the credentials.yml file does not support ERB and thus has no way to read from environment variables.

I could litter my initializers/ directory with pulls from ENV, but that seems very un-railsy as now I have a big block of static configuration in one location (credentials.yml) and dynamic configuration defined in a dozen other locations. Is there a trivial way to enable ERB support in credentials.yml?

3 Likes

I haven’t found any good way to do what you’re describing and I 100% agree with you that it should be The Way.

Encrypted credentials versioned in-repo is a fantastic step up from env vars for test and development credentials. But it should not be the recommended practice for production environments where secrets should be managed by vault/secrets-manager applications and services and supplied to the app via env vars (12-factor).

It seems to me that rails-credentials missed a HUGE opportunity to make the Rails.application.credentials interface be the one funnel for all secrets to be ingested through, both from files and environment. It would have given us a convenient way to require those credentials ( allowing for ENV vars to have static fallbacks, but leveraging the credentials.secret! syntax to fail-early when the secret isn’t found)

Something I intend to experiment with using writing to Rails.application.credentials during environment initialization. This way env vars can be pushed into the credentials store (potentially overriding the encrypted values), and thus allowing the credentials api to be the exclusive mechanism to read secrets post-initialization. I don’t know yet if there will be drawbacks to that approach, but hopefully it’s a bit of a polyfill for the encrypted file supporting ERB directly.

2 Likes