Externalise your configuration

It’s never a good idea to store configuration in code.  Not even in constants, or a transformed config file.

I found that whenever we had the need to create a new environment, we often forgot to update the web.config transforms or the constants in code.  And then there’s always a frantic series of hotfixes to get the correct settings into the code base.  There’s also a security risk when sensitive data lives in a code repository.

Let’s be honest.  We deploy to many environments like:

  • Development
  • UAT
  • Production
  • Jeff’s Dev Env to Figure Out The Timezone Problem

And it’s not easy to maintain in code, especially if we can’t foresee the need for new environments down the road.

After reading the Config section of the 12 Factor App at https://12factor.net/config, you’ll understand why it’s so important to externalise your configuration.

Whenever I package a release for deployment, I want to be sure that I can deploy the same package to any environment without worrying about settings or configuration.

Configuration is the bits that change from environment to environment:

  • Database connection strings
  • Mail settings
  • Queue settings
  • URLs of related services
  • App settings

So what’s the solution?

Environment Variables are OS , platform and code agnostic.

When we set the environment variables as part of a new data center roll out, we can deploy a standard packaged release to the new environment and it will work without code modification.

But setting Environment Variables is such a schlep, Morné!

Not anymore.  (At least not on Windows).  Rapid Environment Editor allows me to add and edit Environment Variables with ease.  Below is an example where I added 3 MyApp variables.  I set these up every time I commission a new virtual machine.

In C#, we can access the Environment Variables like so:

If the Environment Variable is not set, it will return null.

I usually have a static Settings class, where I expose all my Environment Variables as simple strings, integers, booleans, etc.

I also log the settings at startup, masking sensitive data of course.

Then in my application code I can simply use Settings.BaseUrl without thinking about Environment Variables.

Clean separation of configuration and code is not as difficult as it seems, and it will reward you for your efforts down the road.

Happy coding!