(1) You will need Rails 5.1 and above to use this feature.

(2) Use the following command to generate an encryption key and encrypted secrets.

rails secrets:setup

(3) You get 2 files:

  • config/secrets.yml.key
  • config/secrets.yml.enc

(3) The key file contains the encryption key and the enc file contains the encrypted data. You can commit the enc file into git repository but not the key file. To be safe, add a "gitignore" entry for the key file.

(4) To add secrets to the enc file, you need to decrypt it first using this command. You can specify the "EDITOR" of your choice.

EDITOR=pico rails secrets:edit

(5) This brings you to the decrypted version of the file and you can start entering your secrets. Example:

  my_secret: 12345678

(6) Save and exit. The file will be encrypted again with the key.

(7) To have rails decrypt and load the content of this file in the production environment, you need to add this to your config/environments/production.rb file.

config.read_encrypted_secrets = true

(8) Finally, you need to upload your encryption key "secrets.yml.key" to your production server via SFTP. Store it in the config directory.

(9) Reload your server and test if all your secrets are working.