Cowboy in the desert.

Changing website port on each deployment

Paul Stovell

Imagine you're working on a website, and you have a test environment for testers to play with. The tests can take a while, and you want to deploy somewhat frequently, so it would be nice if older versions of the site could remain available even once a newer version has been deployed. You might also like to set some kind of limit - for example, only keeping the three most recent deployments available.

Here's a visual example:

Deployments to different ports

Assuming our release numbers automatically increment, there's a pretty easy solution to this: to decide which port number to use, we can take the last part of the release number, and use that to decide the port number. If we want to limit the number of releases/ports, we can apply the modulo operator to it. We can do this in a PowerShell script step that runs before the deployment, and sets an output variable, which we can then use in the subsequent package step.

Here's what the deployment process would look like:

The deployment process

The Calculate port number step takes the release version number, uses System.Version to parse it, and takes the third component of the version number. It then uses modulo to calculate a port number to use:

# Example: 3.1.1
$release = $OctopusParameters['Octopus.Release.Number']
$version = New-Object System.Version $release
$build = $version.Build    # Major, Minor, Build, Revision

$sitesToKeep = 3
$port = 8080 + ($build % $sitesToKeep)

Write-Host "Website will be available on port: $port"
Set-OctopusVariable -Name "Port" -Value "$port"

Thanks to Set-OctopusVariable, the $port variable will now be available in subsequent steps as #{Octopus.Action[Calculate port number].Output.Port}. When configuring the IIS feature of the package step, we can then set that port number using that variable:

The IIS binding

That's all there is to it! For each deployment, a different IIS website will be used. #{Octopus.Action[Calculate port number].Output.Port} can even be used in an email step to notify the testers that a new release is available to test, and which port number it's on. Output variables and arithmetic for the win!

Loading...