#123 Encrypted Credentials in Rails 5.2


In this episode, we take a look at the Encrypted Credentials of Ruby on Rails 5.2 and how we can patch it so that we can use other YAML files like a development.yml and test.yml.
rails environment encryption 12:01


Source - https://github.com/driftingruby/123-encrypted-secrets-in-rails-52

Additional Notes: To make this more complete, looking at the config_for source, you could add in ERB support and parsing error handling.

config_for# File railties/lib/rails/application.rb, line 227
    def config_for(name)
      yaml = Pathname.new("#{paths["config"].existent.first}/#{name}.yml")

      if yaml.exist?
        require "erb"
        (YAML.load(ERB.new(yaml.read).result) || {})[Rails.env] || {}
        raise "Could not load configuration. No such file - #{yaml}"
    rescue Psych::SyntaxError => e
      raise "YAML syntax error occurred while parsing #{yaml}. " "Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " "Error: #{e.message}"


Terminalrails credentials:help
rails credentials:edit

EDITOR='code --wait' rails credentials:edit
rails c
RAILS_ENV=production rails c
Rails ConsoleRails.application.credentials.aws
config/application.rbrequire_relative 'boot'
require 'rails/all'
require_relative 'rails_env'

module Template
  class Application < Rails::Application
    config.load_defaults 5.2
    config.after_initialize do
      Rails.application.credentials.env = RailsEnv.new
config/rails_env.rbclass RailsEnv
  def initialize
    load_environment_variables unless Rails.env.production?


  def load_environment_variables
    return unless File.exist?(file_name)
    HashWithIndifferentAccess.new(YAML.safe_load(File.open(file_name))).each do |key, value|
      self.class.send :define_method, key.downcase do

  def allow_encrypted_credentials
    self.class.send :define_method, :method_missing do |m, *_args, &_block|

  def file_name
    File.join(Rails.root, 'config', "#{Rails.env}.yml")

they're handing now yeah and that and that and learned real spy what a war that would you take a look in one of the new features that they were including this was included in rails five point lead for now in will's five to the secrets is being removed in favor of credentials the idea with the credentials it's us or your production secrets right there with the new code base we stood up to the repository you will have to worry about any prying eyes because he did it will be encrypted wonder what the deprivation of the secrets in favor of the credentials we're left with the situation of what happens when you have credentials anyone to store and you need to share them with others would result in a place to manage them had previously the secrets enviable fall would've been a good place but the issue with the credentials as a you don't really get the development testing or production and spacing of the head with the secret santa the encrypted secrets sort of look at some work grounds for wii console have a name space environment and still be able to use seen that the credentials so within your application on to the typical her dhabi a couple of different files so we'll be working with that he could get to all-star yeah mall died encrypted then you also have the master key and the master key is going to be the pass rates for the encryption in the crib should have the credentials here whole file this key is not something that you want to commit to europe and repository invite people to chuck and whoever does something that you may wanna share with the dev ops team or you may also want to share with the other developers to that your company if you try to do the secrets and you'll get a message saying that it's been dedicated in favour for the credentials so we got him look at the credentials sell you can see that there's also a barman very bold they didn't have for the master key so we set this up for your c n c d order deployments the hill said the environment variable wells master key to the encryption past friends so let's go ahead and watch her editor so called rails credentials and then edit and if you watch those you'll see that it opens up and even more of the ira or nano whatever the people editor as leverage your uses something like vs code is so have the option to open it up with that and there are so within your you'd see that we have a baby us names based know we have the access key eighty in his secret access key we also have the secret key base if you want to open up in a different matter they need him for contests would editor equals in and enter the editor they you want to use and then run the rails credentials as that in a mistake in though we had credentials and there is follows blank someone did go ahead and closes and instead and when it has a dash dash wait the end of the code what this will do is that it'll tell the whales apartment to hold on before making any changes and to wait for the fall to be closed from the added your code in senegal with that dash dash weight or there you can see that we have our file opened up in a week you make our changes within here once we close a file they will be returned to our prompt in the terminal so it's good starter wills console with excess of credentials we dive wills died application that credentials in a week a basset whichever team that we want so for example we get their secret he pays any kids he returned what really try to get our names basically that the us keys enough we just sat in the aid of us you see there where turn the hash so with the sash to get the access key i'd be you simply just as suddenly as though we better value so this is the basics of how the credentials were louder i'm not quite satisfied with this because if the access key in the secret access key or are being is with an application what do when it is super our homes whenever we're on our development fireman or testing of our men verses the production of armor that would have to be taken into consideration when doing the actual development that to be a real nuisance don't know look at solving this issue in this upset so with them i can fit for only to have a development die young all fall in maybe also way past i am will fall and what to store my credentials in here if i need them and so was something like he did us colleges have a dev underscore one two three is my access key and then three four five as the secret access key no we would have whatever for the secret he based the we would have something similar for the peasant farmer so the main issue is going to be whenever we're developing our application and interacting with the credentials example whenever we're interacting with the aid that the us wouldn't be calling it with enter code jeffrey dahmer view but this just for illustration purposes so we would call or will start application that credentials then the aid of us that this would return or hash however the moms could be in our development of our men this isn't going to work well because it's going to deep artwork production credentials and said of our development wants to what i would like to do is to change out the credentials of it in how it's working so instead of just calling the credentials that he kept us what they call credentials live environment and then got a debbie was an hour to return the same thing the incentive the crafting of looking at the credentials gamble while i want to look at the developing it will fall because this environment is the rails development so i'm pretty good fit for in the application better be i'm going to create a new class and i want to reference it within here we'll call the roof or relative know what is called the spot the wills of armor and then in the application class we need to insert a naked said an actor it has been in its allies with him on a block and we want to set the wheels set application that credentials i'd been two equals to the rails and died new and this is a class i will be creating oh under the typical her will create our real same file but with this fall will create a new class in a class will call the bills and they will create our initial wiser method that will close out the class so we have two situations when we went to water data base here will file or the test just depending on arm barnett so what did create a method called the vote environment variables and we only want to do this if it's not the production of armor is only below this only on our development as a barman by calling unless the rails and farm it is production the ones we have more to fall back to the people of behavior and allow the encrypted credentials somebody create these two private methods and so that we need to load the file and depending on her arm and we'll want to load the development idea will file or maybe will want to let the best idea more file o'grady that the private method now does call this evolving they were going to join the file omar rails root directory in the can fit for her in them we want to get with jim farley we're currently working with the car will set alarm at night yeah more and so for example with their development of armitage know file is being created that we would just want to skip any steps with in here so we can call return or less the foul exist in there we pass in the bombing how does exist then we would want to load the gilmore file and yes it's a gamble fall weak in cali yeah maldives safe mode you know we can open the file with the fall that open it and pass in the bombing a week you luther each one the values that so i'll set the two premieres here as the key in the value in sin el because we set the rails application credentials start environment equal to a new instance at this class we're going to want to return a method to so we get the same kind of functionality the we get with the credentials so we do sell stock class that said that we wanted to find the method that the name is going to be the key that del pais just to get to theirs opera case with a key this is separate friends that said there we just want to return the value they will need of texas and tech center where we all do and that looks good so well call the one of our member of all of us of its our production of garment then we need to allow being cryptic credentials and we're basically going to just pass through how would normally work it so we do something similar were the self class said there we have part of my method in in this case we're gonna try to mimic as best as possible with the credentials will do to a few calls for me that's not too far and within the credentials file which is going to return know we can do a method missing and this is going to take some arguments were the main thing that we're going to use is the method and the arguments is not going to be used in either as if they block as fast so we can color rails application that credentials we can send our method though we were to run and then i will cut that down here it's s. was speed rail this must be file and when the game all fall gets flooded in score too good in the keys as strings so we can call v has with a different access in this way weekend referencing keys as either string or we can reference said as a symbol it said to texas out now i'm going to vote on the left side the production of modern medicine the bills of our been able to production in and watch the rails console and went inside the white to launch the development of armor so the production of arm it but had the bell said application that credentials and sell access many that the us keys and if i run this my development environment and it's all access i'm just like i was able to before lever know the production of garment bag and all environment people hated us and i can then access the keys like that way as well if ed davis on the development of our men you see that now i get my development he's so with them application i don't have to worry about the environment variables rating like that i can simply does reference the credentials type environment that whichever key any in the same thing works with the secret key base in us in each case i'm passing these then as if they were a method nelson that spoke correctly and there's our development of arm and a secret key base and if we do a bet on our production we get our production key so for me personally if i were to using cryptic credentials all would probably in favour this method over you so what does cons steep fall with rails that simply because within the application of the one that were about which a mormon are working with and how wanna make sure that the keys said i am using will be expose all lead to the proper environment so by setting this environment know that not cortex the daily news the production of army keys and let sit there in my development me i'm all for oil the other added benefit to those is that in something like like a waiter for the actors for richard carrier wave a shrine a good reference my environment then the aid of us access key i'd be in there we get our variable from our development yellow file but allah to worry about which of our men are more and it's just going to work throughout the good days that's very similar to how the secret see a whole file work in the past all this over this sub said they keep watching