1

Encountered a problem with environmental variables for the Rails project to pass gitlab CI. Currently, I’m using dotenv gem to store the credentials of my project. Also, I’ve assigned the environment variables in gitlab CI environment. For example, database.yml:

host: <%= ENV['DATABASE_HOST'] %>

.env file:

DATABASE_HOST=somehost

gitlab CI variable:

DATABASE_HOST=somehost

I put .env file in .gitignore and guessed Rails would use variables from gitlab CI. But getting an access error to database. Found a way around, to create local .env files and shared ones as the instruction of dotenv gem suggest. Then put local files in .gitignore and let shared files with credentials for gitlab CI/CD be pushed to repository.

But struggling to understand how secure this approach is? And, in general, what is the best practice for using environment variables/credentials for Rails project and gitlab CI/CD?

Alex Riabukha
  • 187
  • 10
  • Rails encrypted secrets really solve most of the problems that Dotenv did and don't have the risks of cleartext files (like being accidentially committed). – max Apr 29 '21 at 14:13

2 Answers2

0

Ideally .env will include sensitive information in most of the cases. so its not a good practice to commit these into any version control system.

https://dev.to/somedood/please-dont-commit-env-3o9h - Detailed guide here of the risks involved with .env file

Hemali
  • 459
  • 4
  • 8
-1

I usually try to avoid dotenv for CIs because it may represent an overhead for the setup. You can conditionally load dotenv just for some environments but exclude it from the CI/CD. This could be done using a custom ENV variable like so:

Dotenv::Railtie.load unless ENV['GITLAB_CI']

And setting it up in Gitlab envs like GITLAB_CI = true

Regarding your original question, if you really want to have a .env file, you can follow the recommendation from this post answer https://stackoverflow.com/a/55581164/992000, for documentation reasons I'll post them here too:

  1. Create your environment variables in your gitlab repo config
  2. Create setup_env.sh:
#!/bin/bash
echo DATABASE_HOST=$DATABASE_HOST >> .env
  1. Modify your .gitlab-ci.yml. Upsert below to your before_script: section
- chmod +x ./setup_env.sh
- ./setup_env.sh
kinduff
  • 120
  • 2
  • 9
  • Thanks a lot for the reply! If I’ll exclude ENV from CI/CD, do I need to set variables in .gitlab-ci.yml file for each stage like DATABASE_HOST=$DATABASE_HOST and then set the values via Gitlab variables to make everything work? Sorry if that’s a stupid question, feeling completely overwhelmed with these variables – Alex Riabukha Apr 29 '21 at 07:32
  • You need to leave the ENV vars in the CI/CD, and the file from `setup_env.sh` will have available your variables since it's running on the CI/CD. – kinduff Apr 29 '21 at 10:12