Skip to content

Instantly share code, notes, and snippets.

@jasonkarns
Last active May 20, 2026 18:31
Show Gist options
  • Select an option

  • Save jasonkarns/7c2f7c94e101a7c3b63d3eeae00f691a to your computer and use it in GitHub Desktop.

Select an option

Save jasonkarns/7c2f7c94e101a7c3b63d3eeae00f691a to your computer and use it in GitHub Desktop.
require "rake/clean"
CREDENTIALS_FILES = Rake::FileList["config/**/*.yml.enc"]
# Keyfiles for known environments
Rake::FileList.new(%w[test development qa staging production])
.pathmap("config/credentials/%f")
.include(CREDENTIALS_FILES).ext.ext(".key") # plus any other .yml.enc file
.then do |keyfiles|
CLOBBER.add keyfiles # keyfiles should be purged by `rake clobber`
desc "Fetch Rails credentials keys from heroku"
task "credentials:key" => keyfiles
keyfiles.each { file it } # include keyfiles in `rake --all --tasks`
end
# Generate a given config/credentials/ENV.key file
# by pulling the key from the corresponding heroku environment.
# (development and test keys are actually in heroku qa)
#
# This rule allows you to run (for any environment):
# `rake config/credentials/development.key`
rule ".key" do |keyfile|
env = keyfile.name.pathmap("%n") # derive env from keyfile's basename
# keys for dev and test are actually stored on heroku QA
heroku_config_get = if env in "development" | "test"
"heroku config:get --app __APP__ RAILS_MASTER_KEY_#{env}"
else
"heroku config:get --app __APP__ RAILS_MASTER_KEY"
end
rake_output_message heroku_config_get
`#{heroku_config_get}`.then do |key|
next if key.blank?
rake_output_message "writing #{keyfile.name}"
File.write(keyfile.name, key)
end
end
desc "Check keys exist for encrypted credentials files"
task "doctor:credentials_keys" do |t|
CREDENTIALS_FILES.ext.ext(".key").map(&method(:Pathname))
.reject(&:exist?).then do |missing|
rake_output_message <<~MSG if missing.present?
Missing credentials key(s): #{missing}
run 'rake #{t}:fix'
MSG
end
end
task "doctor:credentials_keys:fix" => ["credentials:key"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment