Cowboy in the desert.

Variable substitution in files with Octopus 2.3

Octopus has rich support for variables that can be scoped to specific machines, environments and roles. These can also be substituted into XML App.config and Web.config files at deployment time, by matching variable names to the names of <appSetting> and <connectionString> elements.

In Octopus 2.3, we're extending this to other kinds of files, using the same variable syntax that works throughout the application.

Our sample app is a feed monitoring service that keeps a list of target servers in a JSON file, Config.json:

{
  "Servers": [{
    "Name": "localhost",
    "Port": 1567
  }]
}

When the app is deployed, we'd like to configure the list based on the target deployment environment. The servers in the UAT environment are called FOREXUAT01 and FOREXUAT02.

Variables

We've implicitly set up a ServerEndpoints collection with two items in it, one for each of the servers in the UAT environment.

We can iterate through these in a template file that we'll run at deployment time. So that it doesn't get in the way of development, we'll call it Config.json.template.

{
  "Servers": [
    #{each server in ServerEndpoints}
      {
        "Name": "#{server.Name}",
        "Port": #{server.Port}
      }#{unless Octopus.Template.Each.Last},#{/unless}
    #{/each}
  ]
}

You're probably familiar with the simple form of the #{Variable} syntax. This example uses a few new features added in Octopus 2.0 including #{each} and #{unless} as well.

With Config.json.template included in our app's NuGet package, the next step is to enable the deployment feature.

Enabling the feature

The feature is simple to configure, accepting a list of files that Octopus will perform variable substitution in.

Configuring substitutions

Since we used a different template name from the target file, we'll also add a snippet of PowerShell to replace the original Config.json with the contents of the template file.

PostDeploy

The template will now be run as part of our deployment process.

Execution

And the resulting JSON file is (with whitespace cleaned up a little):

{
  "Servers": [
    {
      "Name": "forexuat01.local",
      "Port": 1566
    },
    {
      "Name": "forexuat02.local",
      "Port": 1566
    }
  ]
}

Happy deployments!


Tagged with: Walkthrough RFC
Loading...