Ruby on Rails Q & A


How to manage secrets and credentials in Rails?

Managing secrets and credentials securely is a crucial aspect of Rails application development. Exposing sensitive data, like API keys or database passwords, can have severe consequences. Rails provides built-in mechanisms to handle secrets and credentials efficiently.


  1. Encrypted Credentials: Starting from Rails 5.2, the framework introduced a way to store secrets in encrypted files. By default, Rails generates `config/credentials.yml.enc`, which is an encrypted file that houses your application’s secrets. This file can be decrypted and edited using the command `rails credentials:edit`. The encryption key, `master.key`, is excluded from version control by default to keep it safe. For production, you should either place the `master.key` securely on the server or use environment variables to provide the encryption key.


  1. Environment Variables: An older and still widely-used method is to rely on environment variables. You can set these variables on your server or local machine and then reference them in your Rails application. For example, you could set a `DATABASE_PASSWORD` environment variable and access it in Rails with `ENV[‘DATABASE_PASSWORD’]`.


  1. Encrypted Secrets: Before the introduction of encrypted credentials, Rails 5.1 offered `secrets.yml.enc` as an encrypted storage for secrets. This method works similarly to encrypted credentials but is now somewhat obsolete given the newer method.


  1. Figaro and dotenv: These are popular gems that allow easier management of environment variables in a Rails app. They facilitate the setup and loading of environment variables, which can then be accessed using the `ENV` object in your application.


  1. Third-party Services: Services like AWS Secrets Manager, HashiCorp Vault, or Azure Key Vault offer more advanced and centralized ways to manage secrets for applications, providing features like rotation, auditing, and fine-grained access control.


It’s crucial to never commit sensitive data directly to your codebase or version control. Always use one of the secure methods provided by Rails or third-party tools to manage your application’s secrets and credentials.

Previously at
Flag Argentina
time icon
Senior Software Engineer with a focus on remote work. Proficient in Ruby on Rails. Expertise spans y6ears in Ruby on Rails development, contributing to B2C financial solutions and data engineering.