Andy Crouch - Code, Technology & Obfuscation ...

Configuring Environments When Building Sites With Jekyll

Photo: Unsplash - Maxwell Nelson

I love static sites for many reasons and Jeyll is still a firm favourite when I need to throw together a simple site. One thing I hadn’t hit with Jekyll before was handling different environment settings and basic secrets. As with most things it was easy if not obvious at first how to handle it. There was also not much reference material other than the documentation. So here is a simple overview.

Setting Up & Configuring Your Configuration Files.

Jekyll gives you the ability to specify what configuration files are processed at build time via the -c command line switch. If you use this then you can pass an argument that is a comma separated list of configuration files. So to add one or more additional configuration files you:

  • Create your secret/environment file. This file should be stored in the root of your project (i.e. the same level as _config.yml). I called mine _environment.yml. This is a standard YAML file which you can add key value pairs such as:
service-url: "https://url-to-this-environments-service"
user-name: "A User"
  • Add the new file(s) to your .gitignore file:
_site
.jekyll-cache
_environment.yml
  • Start your site. Depending on your environment the command can start to get quite long. I generally create a script to start sites locally:
#!/usr/bin/env bash

set -euo pipefail
bundle exec jekyll serve -c _config.yml,_environmet.yml --watch --future --livereload

The other command switches here provide hot reloading of changes (–livereload) which occurs when Jekyll rebuilds automatically on file changes (–watch). If you have dated content then the –future will allow you to see the content locally before the publish date.

So far all really easy. When you come to build your site for publication you can just update the build command to include the

$ jekyll build -c _config.yml,_environmet.yml

Using Your New Configuration Values.

Variables added to these configuration files can be accessed via the site liquid variable. This means they can be added to pages very easily using the standard pattern.

If you need to use these variables in your JavaScript or CSS then don’t forget you can preprocess these files just by adding frontmatter markup to the top of your files such as:

---
layout: null
---

This means you can access the variables from these configuration files using the same markup as above.

$.getJSON("{{ site.ENVIRONMENTVARIABLE  }}", function (data) {};

The popular static site hosts all provide ways to handle these configuration files so make sure you check out their documentation.

If you have any questions about the configuration method described here then let me know via twitter or email.