Aleksandrus
Aleksandrus

Reputation: 1754

Rails 4, Capistrano 3 and Dotenv - How to deploy using server-side .env file

I have a Rails 4 app with Dotenv gem to read variables from the file .env.

There are some variables I've set in order to have a mysql user other than "root" for my rails app, for example:

MYSQL_ROOT_USER='rootuser'
MYSQL_ROOT_PASSWORD='rootpassword'
APP_DATABASE_USER='mydbuser'
APP_DATABASE_PASSWORD='userpassword'

I've also created a bash script to create the mysql user under scripts/database_setup.bash

#!/bin/bash
source ../.env
# creates the user
mysql -u${MYSQL_ROOT_USER} --password="${MYSQL_ROOT_PASSWORD}" -e "CREATE USER '${APP_DATABASE_USER}'@'localhost' IDENTIFIED BY '${APP_DATABASE_PASSWORD}';"
# grants permission
mysql -u${MYSQL_ROOT_USER} --password="${MYSQL_ROOT_PASSWORD}" -e "GRANT ALL PRIVILEGES ON \`myapp\_%\`.* TO '${APP_DATABASE_USER}'@'localhost';"

On the server side, Capistrano deploys to `/home/myuser/apps/myapp/

I have three questions:

  1. Where is the best place to put my server-side .env file? Right now I'm putting it in /home/myuser/apps/myapp/ directory.
  2. How can I tell Capistrano to copy it to Rails root directory?
  3. How can I tell Capistrano to execute my bash script before running migrations?

Upvotes: 3

Views: 2499

Answers (2)

dimitry_n
dimitry_n

Reputation: 3019

If anyone is still having troubles with this, here is how I got my .env working in production with Capistrano 3.5+:

Add your .env.production to /shared directory in production. Then, inside the deployment script, use Capistrano's append command to load linked files from the /shared directory like so:

append :linked_files, ".env.production"

Run the standard deploy (cap production deploy)

You can test whether env vars were appended by launching the rails console in production mode (rails c p) from inside the /current directory.

Upvotes: 6

Dimitris Klisiaris
Dimitris Klisiaris

Reputation: 116

In production environment I think you shouldn't use .env at all.

Probably it's better to put the ENV vars in:

/etc/environment

by writing your variables like this:

export ENV_VARIABLE=value

Upvotes: 6

Related Questions