Creds - Multi Environment Credentials
Rails 5.2.0 is going to introduce Encrypted Credentials as a new way to manage application secrets that shouldn’t be checked in to the repository.
Basically one will be able to call Rails.application.credentials.my_secret_key
to retrieve a value from an encrypted file.
For motivation and the code, details check out this link.
As we are used to having a unified interface for accessing application configuration (by now deprecated Rails.application.secrets
),
one would expect new credentials method to also handle development/test values, but it won’t.
To avoid conditions, like Rails.application.credentials.my_secret_key || "development-fallback"
all over the code,
custom wrapper object looks like a must-have.
Additionally, it would be nice to handle multiple environments like staging with the same unified API.
As a remedy to above problems, Creds gem was built.
After following instructions in the gem Readme, one will be able to call Rails.configuration.creds.my_secret_key
,
which will be backed up by one of encrypted or plain configuration file based on current environment.
The gem is already battle tested on our production servers, but if you feel like adding yet another dependency to your application is too much, check out the small and simple code snippet below, which should give you similar functionality.
class Credentials
include Singleton
class << self
delegate :config, to: :instance
delegate_missing_to :config
end
attr_reader :config
def initialize(env = Rails.env)
@config = if env.in?(["staging", "production"])
Rails.application.encrypted("config/credentials-#{env}.yml.enc")
else
ActiveSupport::InheritableOptions.new(
Rails.application.config_for("credentials-plain", env: env).deep_symbolize_keys
)
end
end
end