Categories
Octopus Deploy PowerShell

Export an Octopus Deploy Variable Set with PowerShell

2 min read

Update 02-13-2020: I created a PowerShell script that exports variable sets to an Excel file. It will create a tab for each set. The script can be found on GitHub – https://github.com/mscribellito/Octopus-Variable-Set-Export.

I received a request last week from a colleague wanting me to export a Variable Set from Octopus Deploy. The web interface does not offer this functionality and if you attempt to copy & paste from the UI, you get something very ugly. Below is what our Test variable set looks like:

Copying/pasting yields the unstructured text below.:

NameValueScope
TestVariable1abcdTestVariable2efghTestVariable3ijklTestVariable4mnop

As a stopgap, I wound up taking a full page screenshot using Chrome’s developer tools. But the developer in me knew there was surely a better way to accomplish this. The PowerShell function below uses the open source Octopus.Client .NET library to do exactly that.

function GetVariableSet {
    Param (
        [Parameter(Mandatory=$true)][string] $OctopusUrl,
        [Parameter(Mandatory=$true)][string] $UserApiKey,
        [Parameter(Mandatory=$true)][string] $VariableSetName
    )
    Process {
        Set-Location 'C:\Program Files\Octopus Deploy\Tentacle'
        Add-Type -Path 'Octopus.Client.dll'
        $endpoint = New-Object Octopus.Client.OctopusServerEndpoint($OctopusUrl, $UserApiKey)
        $repository = New-Object Octopus.Client.OctopusRepository($endpoint)
        $library = $repository.LibraryVariableSets.FindByName($VariableSetName)
        $variableset = $repository.VariableSets.Get($library.VariableSetId);
        $variableset.Variables | Select-Object Name, Value
    }
}

$OctopusUrl = 'http://localhost'
$UserApiKey = 'your-api-key-here'
$VariableSetName = 'Test'

GetVariableSet -OctopusUrl $OctopusUrl -UserApiKey $UserApiKey -VariableSetName $VariableSetName

Executing the function will return something that looks like this:

Name          Value
----          -----
TestVariable1 abcd 
TestVariable2 efgh 
TestVariable3 ijkl 
TestVariable4 mnop 

You can then pipe the output to the Export-Csv cmdlet to generate a CSV file or a different cmdlet to do further processing.