Ruby on Rails 7 Credentials

Ruby on Rails stores the encrypted credentials of your application in the credentials.yml.enc file in the config/ folder. Rails encrypts them using the master key in the config/ folder or the ENV['RAILS_MASTER_KEY'] if you provide one.

You can store them inside the app since they are encrypted. But you must be careful not to commit the master key. You must not lose the master key because, if you lose it, you will also lose access to your secrets.

By default, credentials.yml.enc contains only the secret_key_base, but you can add to it other secrets. You can do this with the command bin/rails credentials:edit. With this command, you'll have temporary access to the unencrypted credentials. Rails will open a temporary .yml file for you to edit in plain text.

When using this command, you need to tell Rails which editor you want to use to edit existing ones or add new credentials. For example, I use the gedit editor. You can choose any editor you want. Run the following command in the terminal:

EDITOR='gedit --wait' bin/rails credentials:edit

You can replace 'gedit' with whatever editor name you want. You must use the --wait flag, otherwise you won't be able to save the changes. Once you've made your changes, save the temporary file and close it. After that, Rails will encrypt the credentials and save them to the credentials.yml.enc file in the config/ folder.

You add new credentials like this:

my_new_key: \aef\xD4\x8C\xE0FzX&\x88H\x80\xC0\xE73\x11.cs\xC1%\xC6'T\xD6\xC0\xE1\xDA\ne\xB3

You can access your credentials in your application as follows:

Rails.application.credentials.my_new_key which returns "\aef\xD4\x8C\xE0FzX&\x88H\x80\xC0\xE73\x11.cs\xC1%\xC6'T\xD6\xC0\xE1\xDA\ne\xB3".
 

Post last updated on April 17, 2022