Ruby, Unicorn, and environment variables Ruby, Unicorn, and environment variables ruby ruby

Ruby, Unicorn, and environment variables


I think your third possibility is on the right track. What you're missing is the idea of a wrapper script, whose only function is to set the environment and then call the main program with whatever options are required.

To make a wrapper script that can function as a control script (if prodEnv use DB=ProdDB, etc), there is one more piece that simplifies this problem. Bash/ksh both support a feature called sourcing files. This an operation that the shell provides, to open a file and execute what is in the file, just as if it was in-lined in the main script. Like #include in C and other languages.

ksh and bash will automatically source /etc/profile, /var/etc/profile.local (sometimes), $HOME/.profile. There are other filenames that will also get picked up, but in this case, you'll need to make your own env file and the explicitly load it.

As we're talking about wrapper-scripts, and you want to manage how your environment gets set up, you'll want to do the sourcing inside the wrapper script.

How do you source an environment file?

envFile=/path/to/my/envFile  . $envFile

where envFile will be filled with statements like

dbServer=DevDBServerwebServer=QAWebServer....

you may discover that you need to export these variable for them to be visble

export dbServer webServer

An alternate assignment/export is supported

export dbServer=DevDBServerexport webServer=QAWebServer

Depending on how non-identical your different environments are, you can have your wrapper script figure out which environment file to load.

case $( /bin/hostame ) in prodServerName )     envFile=/path/2/prod/envFile ;; QASeverName )     envFile=/path/2/qa/envFile ;; devSeverName )     envFile=/path/2/dev/envFile ;;esac. ${envFile}#NOW call your programmyProgram -v -f inFile -o outFile ......

As you develop more and more scripts in your data processing environment, you can alway source your envFile at the top. When you eventually change the physical location of a server (or it's name), then you have only one place that you need to make the change.

IHTH


Also a couple of gems dealing with this. figaro that works both with or without heroku. Figaro uses a yaml file (in config and git ignored) to keep track of variables. Another option is dotenv that reads variables from an .env file. And also another article with all them options.


To spawn an interactive shell (a.k.a. login shell) you need to invoke sudo like this:

sudo -i -u <user> <command>

Also you may use -E to preserve the environment. This will allow some variables to be pased for your current environment to the command invoked with sudo.