We are living as nomad in Cyprus !!
ruby on rails

[Rails] How to use credentials.yml.enc

This is how to use credentials.yml.enc. credentials.yml.enc is used to manage configuration and is designed for more security.


What is credentials.yml.enc

When creating a new application by rails new app ... command in Rails, the following files will be created.

- app/.gitignore

- app/config/credentials.yml.enc

- app/config/master.key

credentials.yml.enc file is used to manage configuration such as environment variable, ID or password. This file is encrypted by config/master.key.

There is config/master.key in .gitignore file so it would not publish to Github, which means master.key is a security information so it should be stored at local.

The contents of credentials.yml.enc and master.key are as below.


$ cat config/credentials.yml.enc

$ cat config/master.key

How to edit credentials.yml.enc

The credentials.yml.enc file is encrypted so you can't edit it directly. So use rails credentials:edit command to edit it.

However, you need to specify environment variable EDITOR on the command. In this time, I am going to edit it by vim command so run rails credentials:edit command using EDITOR=vim.


$ EDITOR=vim rails credentials:edit
  access_key_id: 123
  secret_access_key: 345

# Used as the base secret for all MessageVerifiers in Rails, including the one protecting cookies.
secret_key_base: f250a393dcda613cd5b81a973731e4f38dad918b019e85f7a056553d8caa777d5d0b2bf76a1273f3b2a2ac135b29a47d09164f4264a4eaba6626c15f7f7945d8

Can see the content of credentials.yml.enc. It is set aws and secret_key_base by default.

How to use credentials.yml.enc

Run rails console and then get the values of credentials.yml.enc.


$ rails c
irb(main)> Rails.application.credentials.aws
=> {:access_key_id=>123, :secret_access_key=>345}

irb(main)> Rails.application.credentials.aws[:access_key_id]
=> 123

irb(main)> Rails.application.credentials.aws[:secret_access_key]
=> 345

irb(main)> Rails.application.credentials.secret_key_base
=> "f250a393dcda613cd5b81a973731e4f38dad918b019e85f7a056553d8caa777d5d0b2bf76a1273f3b2a2ac135b29a47d09164f4264a4eaba6626c15f7f7945d8"

If master.key is lost

Unfortunately, you can not open credentials.yml.enc anymore. So be sure to keep it in a safe place.

If you create a new credentials.yml.enc, delete the existing one and then run EDITOR=vim rails credentials:edit command again.

When the above command runs, master.key will be as below:

- If master.key is exist, it will be still used.

- if master.key is not exist, it will be newly created.

Search by keywords

Select Language


Follow us by