Introduction
Purpose: Eliminate hardcoded credentials by storing secrets in an encrypted file (sekrets.yml.enc) and accessing them securely at runtime.
Target Audience: Rails developers and DevOps engineers securing API keys, database passwords, and tokens in Rails apps.
Overview of Sekrets
Definition: Sekrets is a Ruby gem that stores secrets in an encrypted YAML file (sekrets.yml.enc) that is decrypted with a key file (.sekrets.key).
Benefits:
- Prevents committing plaintext secrets to the repository.
- Simple access pattern via
SEKRETS[...]in Ruby and ERB in YAML. - Minimal code changes in existing Rails apps.
Use Cases:
- API keys, DB credentials, webhook tokens, and any secret configuration values.
Prerequisites
- Access to the repository and the Rails app.
- Ability to build/run the local dev environment (e.g., Docker Compose).
- The
.sekrets.keystored securely outside of the repository (e.g., password manager).
Steps
Step 1: Inventory what must be secret
- Identify credentials to be encrypted (API keys, DB passwords, tokens).
- Search for hardcoded occurrences in
.rband.ymlfiles. - Document each key and preferred fallback value (if any).
Step 2: Add secrets (flat or nested) to `sekrets.yml.enc`
- Flat key-value example:
token: 123456- Nested structure example:
slack:
token: 123456- Save and exit; Sekrets re-encrypts the file automatically.
Step 3: Reference secrets in YAML using ERB
- Replace hardcoded values with ERB lookups and an optional fallback.
some_service:
api_key: <%= SEKRETS[:some_service_api_key] || 'fallback-if-missing' %>- Notes:
<%= ... %>executes Ruby during YAML evaluation.SEKRETS[:key]fetches fromsekrets.yml.enc.
Step 4: Use secrets in Ruby code
- Flat key:
api_token = SEKRETS[:sensitive_credential] || 'fallback-if-missing'- Nested key:
slack_token = SEKRETS[:slack][:token]- Loading ERB-enabled YAML in Ruby (if applicable):
config = YAML.load(
ERB.new(File.read(Rails.root.join('path-of-yml-file'))).result
)[Rails.env].symbolize_keys
Step 5: Ensure load order after initializers
- Verify the files that consume secrets run after Rails initializers.
- Restart the app/server to load updated configuration.
Troubleshooting
SEKRETS[:key]returns nil: Check typos; confirm key exists insekrets.yml.encand.sekrets.keyis correct.- Cannot edit
sekrets.yml.enc: Ensure.sekrets.keyis at repo root during edit; verify gem is installed.
Best Practices
- Store
.sekrets.keyonly in a secure vault/password manager; never commit it. - Limit access and rotate keys per policy.
- Add secret scanning to CI to prevent regressions.
Conclusion
By shifting secrets to sekrets.yml.enc and referencing them via SEKRETS[...], Rails apps avoid plaintext credentials in source control and achieve a stronger security posture with minimal code change.