Capistrano: Can I set an environment variable for the whole cap session?

Solution 1:

I have the exactly same problem, but I think this solution is better:

set :default_environment, { 
  'env_var1' => 'value1',
  'env_var2' => 'value2'
}

This works for me like a charm.

Solution 2:

If you need to set a variable on the remote host other than PATH, you should know that sshd only allows certain /etc/profile or ~/.bashrc environment variables by default, for security reasons. As Lou said, you can either do cap shell and use the cap> printenv command, or you can do cap COMMAND=printenv invoke in one command.

If you see the variable when you ssh into the remote shell normally, but you don't see it in the cap printenv command, here's one solution:

  1. Set PermitUserEnvironment yes in your remote server's /etc/ssh/sshd_config file, and restart sshd
  2. Edit the ~/.ssh/environment file for the remote user you are ssh'ing in as, and put your variable(s) there as VARIABLE=value

Now those should show up when you do cap COMMAND=printenv invoke

Solution 3:

I think you have in fact 2 problems:

1) You want to change the PATH on your remote host(s).

Alter/set the path in your .bashrc on your remote host(s) and run cap> printenv, if your path is right, goto #2, else try to add export BASH_ENV=~/.bashrc to your /etc/profile (be careful, ~/.bashrc will then be run for all non-interactive shell for all users)

2) You want sudo to keep your PATH

Run visudo on your remote host(s) and add:

Defaults        exempt_group = "<your_user>"

Solution 4:

I needed to set an environment variable for a specific task to work. The "run" command allows you to pass options which include :env:

run "cmd", :env => { 'name' => 'value' }

In my case, I wanted to add the environment variable to a task that I didn't write, so I used default_run_options which is used by all invocations of run. I added this to the top of my Capfile:

default_run_options[:env] = { 'name' => 'value' }