I'm currently writing a couple Twitter bots for my friends using the Twitter gem for Ruby. My plan was to store the keys for them in a .txt file with the rest of the bot's code on my server, but everything I've read has said the keys shouldn't be readable within the code. Is this secure enough, and if not what would be a good solution? Thanks!
A common approach is to save the environment variables into a file called .env
that is ignored by version control (and therefore won't be included on Github) but read by the code. One gem to help with this is dotenv.
.env
to the .gitignore
file..env
file with all your env varsrequire 'dotenv'
and put Dotenv.load
somewhere at the beginning of your script. In Rails, the require
is unnecessary and you can place the load call in any file in the config/initializers
folderENV
hash from Ruby code. other notes:
see How To Read and Set Environmental and Shell Variables on a Linux VPS
some platforms like heroku have a different mechanism for setting environment variables, such as heroku config:set
or web UIs.
You can set environment variables on a one-off basis using the env
command in bash, for example:
env a=hello b=' world' ruby -e 'puts ENV["a"] + ENV["b"]'
# => hello world
This can give a quick way to configure a program without getting into argument parsing. For example in Rails, you can say rails c test
to open a console using the test environment, but env RAILS_ENV=test rails c
should do the same thing.