Skip to content

Instantly share code, notes, and snippets.

@francescob
Last active June 28, 2021 19:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save francescob/83a8a0fc537cfea1c89b88031d925938 to your computer and use it in GitHub Desktop.
Save francescob/83a8a0fc537cfea1c89b88031d925938 to your computer and use it in GitHub Desktop.
access rails 5.2 encrypted credentials from a script outside the rails app
#First of all, require all of rails (maybe it doesn't need to be all, but for now it is)
require 'rails/all'
#then i need to slightly overwrite a rails method:
def encrypted(path, key_path: "config/master.key", env_key: "RAILS_MASTER_KEY")
ActiveSupport::EncryptedConfiguration.new(
config_path: path,
key_path: key_path,
env_key: env_key,
raise_if_missing_key: nil
)
end
# Then, load the credentials into a YAML object:
credentials = YAML.load(encrypted(File.expand_path("config/credentials.yml.enc"), key_path: File.expand_path("config/master.key")).read)
#Finally, read my credentials:
mail.password = credentials['smtp_password']
@brendon
Copy link

brendon commented Oct 14, 2020

I found I was able to access the credentials just by requiring the environment:

require_relative 'config/environment'

@brendon
Copy link

brendon commented Oct 15, 2020

Even better, this doesn't require loading the Rails environment at all:

require 'active_support/encrypted_configuration'

# Needed for some extra hash magic from Rails
require 'active_support/core_ext/hash/keys'

credentials = ActiveSupport::EncryptedConfiguration.new(
  config_path: "config/credentials.yml.enc",
  key_path: "config/master.key",
  env_key: "RAILS_MASTER_KEY",
  raise_if_missing_key: true
)

This assumes the file you're running is in the root of the Rails project (in my case a Rack application).

You can then access the credentials using object notation: credentials.special_secret_key

@francescob
Copy link
Author

very nice, thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment