meolic
meolic

Reputation: 1207

Specify environment variables for bundle exec

I have seen two different ways to specify environment variables when execute bundle exec. Which one is correct on Linux? Maybe both? I am looking for general answer, I know that in this particular case (updating Redmine) specifying RAILS_ENV may be even unnecessary.

bundle exec rake db:migrate RAILS_ENV=production
RAILS_ENV=production bundle exec rake db:migrate

Upvotes: 4

Views: 8751

Answers (1)

Holger Just
Holger Just

Reputation: 55888

Both options are possible to define environment variables for rake tasks. However, for other executables (such as the rails executable), only the variant to define the variables before the executable is supported.

What is happening here is that when you specify the environment variables at the start, your shell (bash, zsh, ...) set those environment variables for the newly started process. This can be done for any process. processes also inherit the environment variables defined earlier in the shell. A third option could thus be to run this in your shell:

export RAILS_ENV=production
bundle exec rake db:migrate

Now, if you specify the variables as arguments to the rake executable, the shell does not affect, read, or write those. Instead, rake itself inspects its given process arguments and sets the environment variables for its own process before handing control to the actual rake task (db:migrate in this case).

To be more consistent in your ability to define environment variables for the various executables, I personally tend to stick to the option to set environment variables in the shell, rather than using the rake feature to parse its arguments.

Finally, regarding your remark that the RAILS_ENV environment variable might not be necessary here: that is likely not true. Rails applications such as Redmine define different behavior based on the loaded environment, including the database they connect to (as defined in the config/database.yml file), other settings (as defined for Redmine in config/configuration.yml) and internal parameters such as logging verbosity and handling of exceptions. As such, you most likely want to always use RAILS_ENV=production everywhere since Rails (and Redmine) default to the development environment if nothing is specified.

Upvotes: 5

Related Questions