cfenv for Easier NodeJS on Cloud Foundry

Now I’m working at IBM I am making extensive use of their Bluemix Platform, which is based on Cloud Foundry. The way that Cloud Foundry is set up is actually very neat, with everything you need contained in JSON structures within environment variables. Parsing out those values can be a pain however, so I thought I’d share the library that’s helping me the most with this: cfenv.

Cloud Foundry Environment Variable Structure

In one of my apps, which has both a Cloudant (CouchDB) database, and a RabbitMQ queue, the configured environment looks something like this (use the cf env command to see the environment values available to your app):

{
 "VCAP_SERVICES": {
  "compose-for-rabbitmq": [
   {
    "credentials": {
     "ca_certificate_base64": "LS0tLS1...",
     "db_type": "rabbitmq",
     "deployment_id": "585164fad9718500180011b3",
     "name": "bmix_lon_yp_49c23a93_1583_4971_b0f1_5cd638c37a78",
     "uri": "amqps://admin:[email protected]:20264/bmix_lon_yp_49c23a93_1583_4971_b0f1_5cd638c37a78",
     "uri_admin": "https://bluemix-sandbox-dal-9-portal4.dblayer.com:20264",
     "uri_admin_1": "https://bluemix-sandbox-dal-9-portal5.dblayer.com:20264",
     "uri_direct_1": "amqps://admin:[email protected]:20264/bmix_lon_yp_49c23a93_1583_4971_b0f1_5cd638c37a78"
    },
    "label": "compose-for-rabbitmq",
    "name": "guestbook-messages",
    "plan": "Standard",
    "provider": null,
    "syslog_drain_url": null,
    "tags": [
     "big_data",
     "data_management",
     "ibm_created"
    ]
   }
  ]
 }
}

What the above is telling me is that inside a variable called VCAP_SERVICES, I’ll find the following information relating to my RabbitMQ service that this app uses. It’s entirely possible to parse the JSON and pull out the values the app needs, but it’s clunky especially with hyphenated key names! Instead, the cfenv library makes this super simple.

The code for this is on GitHub if you want to see it in context but essentially it boils down to:

Bring in the dependency:

var cfenv   = require('cfenv');

Next, parse the environment variable into something we can use:

    var appEnv = cfenv.getAppEnv()

Finally, go ahead and use those variables that are now in the appEnv (you might like to make this a constant rather than a variable since updating it will do nobody any good):

    rabbitmq_url = appEnv.getService('guestbook-messages').credentials.uri;

Hopefully this shows how the cfenv library makes it easy to work with the Cloud Foundry environment variables and will remind me how to solve this next time I run into problems parsing a complicated data structure! There are equivalents for other languages too, for example if you use PHP try installing cf-helper-php via composer.

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.