Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use environment variables in Rake task

task :some_task, :environment do |t, args|
  puts Rails.env #=> development, production, etc
  puts ENV #=> {}
end

I set some environment variables (either via a local .env, or via Heroku Config via Herokusan), such as which AWS bucket to use, and I want to reference them in the rake task, but ENV is an empty hash. I know something related to environment gets done because of the :environment task dependency and that Rails.env has a value, but I'm not clear on the details.

So, how can I use ENV in a Rake task?

like image 485
Narfanator Avatar asked Mar 28 '13 19:03

Narfanator


People also ask

What is environment rake task?

Including => :environment will tell Rake to load full the application environment, giving the relevant task access to things like classes, helpers, etc. Without the :environment , you won't have access to any of those extras.


1 Answers

Two good ways to do it:

Use Heroku's "Foreman" tool. Put all your environment variables into .env:

VAR=value

and run foreman run rake some_task.

Or (and, I'd recommend this way), using the "Figaro" gem. Put your vars into config/application.yml:

VAR: value

and that's it; rake some_task.

I'd recommend the latter, if only because rake figaro:heroku will push your env up as it's specified in application.yml

like image 166
Narfanator Avatar answered Sep 28 '22 01:09

Narfanator