Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using dotenv variables inside capistrano 3 custom task

I'm trying to create capistrano task that will show a variable set by dotenv from .env file

the task:

namespace :test do
  task :env do
    on roles(:app) do
      info ENV['TEST_ENV'].inspect
    end
  end
end

.env file:

TEST_ENV='confusing'

running the task:

$ cap staging test:env
DEBUG [37c8a9e6] Running /usr/bin/env [ ! -d ~/.rbenv/versions/2.0.0-p353 ] on x.x.x.x
DEBUG [37c8a9e6] Command: [ ! -d ~/.rbenv/versions/2.0.0-p353 ]
DEBUG [37c8a9e6] Finished in 14.776 seconds with exit status 1 (failed).
 INFO nil

this is under a working capified rails 4 app (I can run cap staging deploy just fine)

anyone can tell me what am I missing please?

edit:

as it might not be clear enough, what I actually need is to access .env in my local machine, the actual case:

I store a secret api key inside .env and it will be used to notify external api service after deploy, the api key itself isn't supposed to be stored anywhere else and is app exclusive (each app have its own key) so it's not a good idea to store it permanently in local env

like image 386
Roy Avatar asked Jan 23 '14 13:01

Roy


Video Answer


2 Answers

I found it, I need to use Dotenv.load before using ENV and add require 'dotenv' in Capfile

it's actually documented in dotenv readme: https://github.com/bkeepers/dotenv#sinatra-or-plain-ol-ruby

should have read it more carefully..

like image 61
Roy Avatar answered Sep 23 '22 03:09

Roy


At this moment, your rails application are not running,

or at least you capistrano task is not running inside rails context.

Because of that, your .env is not loaded into ENV yet.

Beside this, your ruby code ( aka your task ) is executed on client side ( your machine ).

One way to get environment variable os remote machine is using bash:

    namespace :test do
      task :env do
        on roles(:app) do
          info caputure('echo $TEST_ENV')
        end
      end
    end
like image 38
guiceolin Avatar answered Sep 22 '22 03:09

guiceolin