rubyenvironment-variablescapistranocapistrano3env

Capistrano read from .env on deployment server


I am trying to perform a database backup as part of a Capistrano (v3) deployment script (for a NON-Rails app).

The script works fine -- if I hard-code database config into it.

Now I want to load in the database config from a .env file. On my local machine, my .env file (in the repo root next to the Capfile) reads as follows:

DB_NAME='local_name'
DB_USER='local_user'
DB_PASSWORD='local_pw'
DB_HOST='127.0.0.1'

On the server, the .env file (which Capistrano has placed in the shared folder & symlined to from the current folder) reads as follows:

DB_NAME='dev_name'
DB_USER='dev_user'
DB_PASSWORD='dev_pw'
DB_HOST='127.0.0.1'

However, when running cap deploy, I get the following:

INFO [292e2535] Running /usr/bin/env mysqldump -u local_user --password='local_pw' --databases local_name -h 127.0.0.1 | bzip2 -9 > /var/www/vhosts/xxxxx/backups/database_local_name_2014-05-29_22:52:07.sql.bz2 on <server>

I.e. it's using my local .env file, when actually I'd like it to load the .env file that is present on the server. I do not want all of my team to have to manage a separate .env.production file if at all possible!

The relevant portion of my script is as follows (using the Dotenv gem):

require 'dotenv'
Dotenv.load '.env'
username, password, database, host = ENV['DB_USER'], ENV['DB_PASSWORD'], ENV['DB_NAME'], ENV['DB_HOST']

Any help would be greatly appreciated!


Solution

  • You can use the Dotenv::Parser.call(string). I am using with Capistrano 2.14 (this is older version!)

    desc <<-desc
      ENV test
    desc
    task :test do
      text = capture "cat #{shared_path}/.env"
      ENV2 = Dotenv::Parser.call(text)
      puts ENV2['DB_NAME']
    end