DEV Community

Samuel Lubliner
Samuel Lubliner

Posted on

Storing credentials securely in environment variables

Environment variables: live on the computer somewhere separate from our code, and code will read the variables to access it

Access environment variables via the ENV hash

if there was an environment variable on your computer called zebra that had a value of giraffe, this is how you would access it from within Ruby:

ENV.fetch("ruby_var") # => "env_var_cont"
Enter fullscreen mode Exit fullscreen mode

Storing credentials securely in your ENV variable to get access in your Codespaces project

Adding a secret:

  1. In the upper-right corner of any page, click your profile photo, then click Settings.

  2. In the "Code, planning, and automation" section of the sidebar, click Codespaces.

  3. To the right of "Codespaces secrets", click New secret.

  4. Under "Name", type a name for your secret.

  5. Under "Value", type the value of your secret.

  6. Select the "Repository access" drop-down menu, then click a repository you want to have access to the secret. Repeat for every repository you want to have access to the secret.

ENV.fetch("ENV_VAR_NAME")

Stop and Start your workspace again to pick up the new entry

Test by running irb and fetching the key you added

Local setup, dotenv
dotenv-rails gem is a slightly better way than storing your secrets in your bash profile;

In your .gitignore file, make sure that there’s a line somewhere with /.env*

Make a git commit for the above change, if necessary.

Create a file in the root folder of the app called .env

Then add your secrets to it:

 CLOUDINARY_CLOUD_NAME="paste your cloud name here"
 CLOUDINARY_API_KEY="paste your api key here"
 CLOUDINARY_API_SECRET="paste your api secret here"
Enter fullscreen mode Exit fullscreen mode

/.env* is included in the .gitignore file, and doesn’t exist as far as git is concerned. Safe to put sensitive information in it

Restart bin/dev and you should now be able to access these values from the ENV hash, e.g. ENV.fetch("CLOUDINARY_CLOUD_NAME")
More about dotenv

Top comments (0)