Using Environment Variables in Node.js with Amazon OpsWorks

Using Environment Variables in Node.js with Amazon OpsWorks

Hold on Cowboy

This blog post is pretty old. Be careful with the information you find in here. It's likely dead, dying, or wildly inaccurate.

I find it hard to believe that I could not find a good article online of how to get env vars working in OpsWorks. I think even more astounding is that it takes a custom recipe to accomplish this end. When you host your app on Heroku, you can easily just do an heroku config:set FOO=bar with the Heroku Toolbelt. In AWS OpsWorks, it’s a little more involved. Let’s see just how.

The Key Elements

Add a Custom Chef Cookbook to your Stack Settings

Here you are going to have to go to your Stack Settings and Edit them. You will see a section to Use custom Chef cookbooks. In this section you are going to choose git as the repository type and https://github.com/vlamic/OpsWorksEnvy.git as the repository URL. NOTE: You are more than welcome to fork this repo and use your fork.

Config Management

Add your JSON

Now while we are in the Stack Settings, we’ll add our Custom JSON that will specify our environment variables. Replace the information below with your own. NOTE: There are two sections below, one for the server instance, and one specifically for each App

{
  "environment_variables": {
    "NODE_ENV": "production"
  },
  "deploy": {
    "THE_SHORT_NAME_OF_YOUR_APP": {
      "environment_variables": {
        "NODE_ENV": "production",
        "PORT": 80,
        "mongoUri": "mongodb://xxxx",
        "adminUsername": "admin",
        "adminPassword": "password",
        "s3Key": "XXX",
        "s3Secret": "XXX",
        "s3Bucket": "BUCKET",
      }
    }
  }
}

Integration Custom Recipe into your Layer.

I think this was the hard part for me since I’m not real familiar with Ruby or Chef. Go to Layers, then Recipes, then Edit. Now you want to add environment_variables::default to the Deploy section. Then press the + to add it. When you are done, it will look like this.

Custom Recipe

Deploy your App

Now when you deploy your app, those variables will be in process.env. Use these like a boss and have pity on those that include passwords and such in their app source code.

One More Thing.

This is a plug for the best friend of your Environment Variables, the Node.js module nconf. It makes using these variables in your app a snap. I usually have it set up like this in my apps. That way you can easily provide env vars in a gitignore’d file in your app directory.

// Load config vars from command line, ENV, file, and defaults
nconf.argv()
     .env()
     .file(YOUR_APP_ROOT_DIR/.env.json)
     .set('VERSION', pkg.version);

Just to be sure, I have this in my .gitignore file to ignore anything that starts with .env...

.env*

Happy Camping.