Steven 30.12.2021
Rails has a very easy way to store all kinds of credentials., based on the use of two files:
Example credentials to be stored in credentials.yml.enc
With this approach, there is no need to work with environment variables.
Example credentials.yml file. Note: the file is always encrypted before storage, you can verify this by looking at the file extension credentials.yml.enc
### config/credentials.yml
# Used as the base secret for all MessageVerifiers in Rails, including the one protecting cookies.
secret_key_base: <your-secret-hash>
# used for e.g. ActionMailer email delivery
email:
user: <email-adress>
password: <email-pass>
# database access in production environment
production:
database:
database: <production-database-name>
username: <database-user>
password: <database-pass>
host: <database-host>
# ActiveStorage file storing in the cloud
aws:
access_key_id: <aws-key-id>
secret_access_key: <aws-secret-key>
Open the credentails file from within your application folder user.
$ rails credentials:edit
With this command, rails takes the master.key, decrypts credentials.yml.enc and opens it in the editor. As soon as you close the file, rails encrypts again (adding the *.enc extension).
In case you’re on Windows, you can set the editor of choice using:
# regular command prompt
> SET EDITOR="C:/Program Files (x86)/Notepad++/notepad++.exe"
> rails credentials:edit
# Windows powershell
> $env:EDITOR="notepad"
> rails credentials:edit
Access the credentials using Rails.application.credentials.dig() command:
### config/storage.yml
amazon:
service: S3
access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
region: <your-region-here>
bucket: <bucket-name>
### config/environments/production.rb
config.action_mailer.smtp_settings = {
address: '<email-server>',
port: '<port>',
domain: '<your-domain>',
user_name: Rails.application.credentials.dig(:email, :user),
password: Rails.application.credentials.dig(:email, :password),
authentication: :plain,
tls: true,
enable_starttls_auto: true
}
Rails stores secrets in config/credentials.yml.enc, which is encrypted and hence cannot be edited directly. Rails uses config/master.key or alternatively looks for the environment variable ENV[“RAILS_MASTER_KEY”] to encrypt the credentials file. Because the credentials file is encrypted, it can be stored in version control, as long as the master key is kept safe.
https://edgeguides.rubyonrails.org/security.html#custom-credentials
This article details how to setup Nginx and Passenger to run a Rails app in production environment on a Ubuntu machine. It uses Ubuntu 20.04 LTS, Nginx 1.18 and Phusion Passenger 6.0.12.
Comment