Ruby rails: secrets and key-values

From wikinotes
Revision as of 15:22, 8 August 2020 by Will (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The rails convention is to store dummy secrets for development/testing,
and retrieve secrets from environment variables in production.

Locations

{project}/config/secrets.yml configure secrets
{project}/config/application.rb configure key/values

Secrets

Configuration

# config/secrets.yml
development: &dev
  key: foo

testing: *dev

production:
  key: <%= ENV["key"] =>

This file is preprocessed with eruby

Usage

# access secret 'secret_name' for the current rails environment
password = Rails.application.secrets.{secret_name}

Key-Values

Secrets are great for sensitive information, but are overkill for other types of info. For non-secret information use Application.config.

Configuration

config/application.rb is designed to rails and it's various gems,
but you can also define your own keys here, that will be available to the entire application.

require File.expand_path('../boot', __FILE__)
require 'rails/all'

Bundler.require(*Rails.groups)

module Project
  class Application < Rails::Application
    # examples of rails config
    config.i18n.default_locale = :de
    config.active_record.raise_in_transactional_callbacks = true

    # example custom key/vals
    config.x.project_name = "my awesome project"
  end
end

Usage

Rails.configuration.x.project_name