Many times we have API credentials or other sensitive information that we don’t want to paste directly into our code, because then the information would be exposed on GitHub. Unsavory types like to scrape GitHub for sensitive information like API keys and run up huge bills for compromised users.
Instead, we’ll store this information in environment variables, which means it lives on the computer somewhere separate from our code, and then our code will read the variables to access it.
In Rails, the way to access environment variables is via the ENV
hash. The ENV
hash is available to you everywhere — views, controllers, models, rails console
, rake tasks, etc. The keys in the hash are the names of any environment variables that exist on the computer you’re using, and the values are the contents of the variables.
For example, 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 Rails:
ENV.fetch("zebra") # => "giraffe"
But how do we create the environment variables and store our secrets in them?
From your Gitpod dashboard, click on your icon in the top right corner and select “User Settings”:
Now click on the “Variables” tab and select “New Variable” in the “Environment Variables” section:
The “Name” is how you want to name the variable (e.g., GMAPS_KEY
) and the “Value” is the API token you’ve been provided. The “Scope” entry is to specify which project(s) on Gitpod will have access to this credential. If you want to allow the use of this credential in all workspaces you can set it to */*
:
Stop and Start your workspace again to pick up the new entry.
You can test to make sure you’ve configured everything properly by running rails console
and fetching the key you added.
ENV.fetch("GMAPS_KEY")
and we should see output of
=> "replace_me_with_your_key"
If you’re getting a "Key not Found"
error, make sure that you specified the correct “Scope”. If you need to update that on the “Environment Variables” page, make sure you Stop and Start your workspace again.
You can use this pattern throughout your Rails app to store and use sensitive info but prevent it from showing on GitHub when you push your code up.
If you’re not using Gitpod, there’s a slightly better way than storing your secrets in your bash profile; the dotenv-rails
gem.