Skip to content

Instantly share code, notes, and snippets.

@stympy
Last active March 4, 2025 15:21
Show Gist options
  • Save stympy/10ed61d5744da5b1e1456783675e32ce to your computer and use it in GitHub Desktop.
Save stympy/10ed61d5744da5b1e1456783675e32ce to your computer and use it in GitHub Desktop.
Loading multiple encrypted credentials files in Rails
aws:
access_key_id: 123
secret_access_key: 456
Credentials.load!
Credentials.get(:aws)
=> {:access_key_id => 123, :secret_access_key => 456}
module Credentials
module_function
# Fetch a value from the credentials file. Each argument will descend another
# level into the hash.
# Example: For a hash of { "github" => { "client_id" => "123" } },
# get("github", "client_id") will return "123"
def get(*args)
app.credentials.dig(*args.map(&:to_sym)).tap do |val|
val.gsub!('\\n', "\n") if val.is_a?(::String)
end
end
# This is a drop-in replacement for ENV['SOME_KEY']
# It will first look in ENV, then in the credentials file.
# Example: Credentials['GITHUB_CLIENT_ID'] will return the value of
# ENV['GITHUB_CLIENT_ID'] or Rails.application.credentials.dig("github", "client_id")
def [](key)
::ENV[key.to_s] || get(*key.to_s.split('_', 2).map(&:downcase))
end
# Add any encrypted credentials found in config/credentials/[Rails.env] to
# the main credentials hash.
def load!
key_path = app.credentials.key_path
app.credentials.config.update(
::Dir["config/credentials/#{::Rails.env}/*.yml.enc"].each_with_object({}) do |f, h|
h.update(
app.encrypted(f, key_path: key_path).read.then do |data|
::YAML.safe_load(data, symbolize_names: true)
end
)
end
)
end
def all
app.credentials.config
end
def app
::Rails.application
end
end
rails encrypted:edit config/credentials/development/aws.yml.enc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment