Recently I was experiencing an issue with the Play 2 Framework where it could not find environment variables on Mac OS when compiled within IntelliJ IDEA. The solution turned out to be simple, but could be inconvenient when an environment variable is used in many programs.

Here's how it happened: While perusing a tutorial on Heroku, I read that it is not a good idea to store sensitive connection information (i.e. database user and password, API keys, etc.) in your config files. In fact, it is recommended that, when storing information in a config file you ask yourself the question: if I open sourced my application today, would any credentials be compromised?

So, as a responsible programmer, I decided to move all my credentials into my environment, i.e. into my .bash_profile file:

# PostgreSQL
export PGSQL_USER=user
export PGSQL_PASSWORD=password

# AWS
export AWS_ACCESS_KEY_ID=id
export AWS_SECRET_KEY=secret

...and updated my application.conf in Play 2 to:

# Database configuration
# ~~~~~ 
# You can declare as many datasources as you want.
# By convention, the default datasource is named `default`
#
db.default.driver=org.postgresql.Driver
db.default.url="jdbc:postgresql://localhost/db_name"
db.default.user=${?PGSQL_USER}
db.default.password=${?PGSQL_PASSWORD}

# Amazon Web Services
# ~~~~~
aws.accessKeyId=${?AWS_ACCESS_KEY_ID}
aws.secretKey=${?AWS_SECRET_KEY}
s3.https=true
s3.bucket=bucket-name

However, once I did this and re-compiled it in IntelliJ, I started to get a whole bunch of errors from Play 2 at runtime saying that it couldn't find the configuration keys that it had no problem finding before. After some poking around, I realized that these errors only seemed to be occurring when I compiled my project in IntelliJ, and not if I compiled it via play run from the terminal.

A little more digging revealed that this was an issue for Mac OS X in general.

The solution? Unfortunately, there is no general solution. That is, there's no way (that I know of) to get all apps to see your environment variables as you'd expect. However, IntelliJ does provide a facility for defining per-configuration environment variables. Here's how to do it.

First, in the IntelliJ toolbar, click Edit Configurations.

Edit Configurations

Next, find the configuration that is using the environment variables, and click the icon beside the "Environment variables" field.

Environment Variables

Now, add all the environment variables your application is looking for and click "OK".

Environment Variables

That's it, your IntelliJ program should now properly find your environment variables!