How to set environment variables that can be referenced by Apache, shells and cron jobs

In some cases, environment variables are used to store configuration information. If the values are referenced from different sources, such as through a web server and on the command line, it is a good idea to define them in a single place and gracefully make them available.

This is one way to set the environment variables in one place, then source them into accounts for use (CentOS 6.4):

1. Create /opt/webapp/etc/appconfig/common and put the environment variables in it

export TEST_ENV_VAR="Test Environment Variable"

2. Add these two lines to /opt/webapp/etc/sysconfig/httpd

if [ -f /opt/webapp/etc/appconfig/common ]; then
. /opt/webapp/etc/appconfig/common
fi

3. Add these two lines to /etc/sysconfig/httpd

if [ -f /opt/webapp/etc/sysconfig/httpd ]; then
. /opt/webapp/etc/sysconfig/httpd
fi

4. Add this line to /etc/httpd/conf.d/webapp.conf (webapp Apache conf file)

PassEnv TEST_ENV_VAR

4. Restart Apache with service httpd restart

5. Test with http://webapp/phpinfo.php (<?php phpinfo(); ?>

6. Add these two lines to /home/admin/.bashrc - or whatever the account is that will use the variables.

if [ -f /opt/webapp/etc/appconfig/common ]; then
. /opt/webapp/etc/appconfig/common
fi

7. Test with echo $TEST_ENV_VAR

What this does is creates a common place to store the environment variables and makes them accessible to both Apache and the shell of admin (and any other account that includes them). That way, when a script is run as a cron job or on the command line, it has the environment variables all set. If new environment variables are needed, or if they change, the common file is updated as well as any others that reference the new variables. Then you restart Apache.