The Twelve-Factor App says that web applications should retrieve their configuration from environmental variables. This practice has been rapidly adopted by modern PaaS services to enable simple configuration changes.
With Consul, it is simple to bring this practice to your own datacenters. If you use a PaaS for some aspects of your infrastructure but not all of it, Consul is a great way to centralize configuration data.
In this post, we show how Consul and envconsul can be used to set configuration values and trigger automatic restarts on configuration changes, all without any modifications to your applications.
Why Environmental Variables?
According to the Twelve-Factor app, environmental variables should be used for web application configuration. They have a number of benefits when compared against configuration files or mechanisms such as Java System Properties:
Environmental variables are a language- and OS-agnostic standard.
Environmental variables are more difficult to accidentally commit to a code repo.
Environmental variables are easy to change between environments such as development, staging, QA.
Environmental variables are easy to set and update regardless of deploy.
Complete PaaS solutions such as Heroku expose helpful APIs to automatically set/get environmental variables for an application.
When deploying applications manually, the story has historically been a bit more complicated. With Consul, it is just as easy to set and read configurations for developers, and easy to support and maintain as an operations engineer.
Consul K/V and Envconsul
It is clear to see how to set and retrieve configuration data, but it isn't clear how this configuration data can become environmental variables for an application. envconsul is a lightweight solution that solves this problem.
With envconsul, environmental variables are stored in Consul KV under some prefix (separated by "/"). For example, to configure our service "foo" we might store configuration like this:
$ curl -X PUT -d 'false' http://localhost:8500/v1/kv/foo/enabled true
This stores the value
false in the key
Then, with envconsul, we can turn these keys into environmental variables:
$ envconsul foo env ENABLED=false
envconsul is a very UNIX-friendly application. It takes two mandatory arguments: a KV prefix to find data and then another application to run along with its arguments. In the above example, we tell envconsul that our configuration is under the prefix
foo and we want to run the application
env, which simply outputs the environmental variables.
In the result, you can clearly see that