Save Octopus Output Variable

Octopus.Script exported 2021-10-21 by harrisonmeister belongs to ‘Octopus’ category.

Saves an output variable to the given project / library variable set

Parameters

When steps based on the template are included in a project’s deployment process, the parameters below can be set.

API Key

StepTemplate_ApiKey =

Provide an Octopus API Key with appropriate permissions to save the variable

Deployment Step

StepTemplate_DeploymentStep =

Select the step with the output variable

Variable Name

StepTemplate_VariableName =

Name of the variable used when it was set

Note: The same name will be given to the saved variable

Variable Set Type

StepTemplate_VariableSetType = project

If the output variable is being saved to a project or library variable set

Variable Set Name

StepTemplate_VariableSetName = #{Octopus.Project.Name}

Name of the project or library variable set where the output variable should be saved

Is Sensitive?

StepTemplate_IsSensitive = False

If the variable should be marked as sensitive and the value masked from logs

Script body

Steps based on this template will execute the following PowerShell script.

$ErrorActionPreference = 'Stop'

$StepTemplate_BaseUrl = $OctopusParameters['#{if Octopus.Web.ServerUri}Octopus.Web.ServerUri#{else}Octopus.Web.BaseUrl#{/if}'].Trim('/')
if ([string]::IsNullOrWhiteSpace($StepTemplate_ApiKey)) {
    throw "The step parameter 'API Key' was not found. This step requires an API Key to function, please provide one and try again."
}

function Invoke-OctopusApi {
    param(
        [Parameter(Position = 0, Mandatory)]$Uri,
        [ValidateSet("Get", "Put")]$Method = 'Get',
        $Body
    )
    $requestParameters = @{
        Uri = ('{0}/{1}' -f $StepTemplate_BaseUrl, $Uri.TrimStart('/'))
        Method = $Method
        Headers = @{ "X-Octopus-ApiKey" = $StepTemplate_ApiKey }
        UseBasicParsing = $true
    }
    if ($null -ne $Body) { $requestParameters.Add('Body', ($Body | ConvertTo-Json -Depth 10)) }
    Write-Verbose "$($Method.ToUpperInvariant()) $($requestParameters.Uri)"   
    Invoke-WebRequest @requestParameters | % Content | ConvertFrom-Json | Write-Output
}

function Test-SpacesApi {
	Write-Verbose "Checking API compatibility";
	$rootDocument = Invoke-OctopusApi 'api/';
    if($rootDocument.Links -ne $null -and $rootDocument.Links.Spaces -ne $null) {
    	Write-Verbose "Spaces API found"
    	return $true;
    }
    Write-Verbose "Pre-spaces API found"
    return $false;
}

if(Test-SpacesApi) {
	$spaceId = $OctopusParameters['Octopus.Space.Id'];
    if([string]::IsNullOrWhiteSpace($spaceId)) {
        throw "This step needs to be run in a context that provides a value for the 'Octopus.Space.Id' system variable. In this case, we received a blank value, which isn't expected - please reach out to our support team at https://help.octopus.com if you encounter this error.";
    }
	$baseApiUrl = "api/$spaceId" ;
} else {
	$baseApiUrl = "api" ;
}

function Get-OctopusSetting {
    param([Parameter(Position = 0, Mandatory)][string]$Name, [Parameter(Position = 1, Mandatory)]$DefaultValue)
    $formattedName = 'Octopus.Action.{0}' -f $Name
    if ($OctopusParameters.ContainsKey($formattedName)) {
        $value = $OctopusParameters[$formattedName]
        if ($DefaultValue -is [bool]) { return ([System.Convert]::ToBoolean($value)) }
        if ($DefaultValue -is [array] -or $DefaultValue -is [hashtable] -or $DefaultValue -is [pscustomobject]) { return (ConvertFrom-Json -InputObject $value) }
        return $value
    }
    else { return $DefaultValue }
}

$outputVariableKey = "Octopus.Action[${StepTemplate_DeploymentStep}].Output.${StepTemplate_VariableName}"
if (!$OctopusParameters.ContainsKey($outputVariableKey)) {
    throw "Variable '$StepTemplate_VariableName' has not been output from '$StepTemplate_DeploymentStep'"
}
$isSensitive = [System.Convert]::ToBoolean($StepTemplate_IsSensitive)
$variableType = if ($isSensitive) { "Sensitive" } else { "String" }

$variableValue = $OctopusParameters[$outputVariableKey]
Write-Host "Name: $StepTemplate_VariableName"
Write-Host "Type: $variableType"
Write-Host "Value: $(if ($isSensitive) { "********" } else { $variableValue })"
Write-Host ' '

Write-Host "Retrieving $StepTemplate_VariableSetType variable set..."
if ($StepTemplate_VariableSetType -eq 'project') {
    $variableSet = Invoke-OctopusApi "$baseApiUrl/projects/all" | ? Name -eq $StepTemplate_VariableSetName | % { Invoke-OctopusApi $_.Links.Variables }
}
if ($StepTemplate_VariableSetType -eq 'library') {
    $variableSet = Invoke-OctopusApi "$baseApiUrl/libraryvariablesets/all?ContentType=Variables" | ? Name -eq $StepTemplate_VariableSetName | % { Invoke-OctopusApi $_.Links.Variables }
}
if ($null -eq $variableSet) {
    throw "Unable to find $StepTemplate_VariableSetType variable set '$StepTemplate_VariableSetName'"
}

$variableExists = $false
$variableSet.Variables | ? Name -eq $StepTemplate_VariableName | % {
    Write-Host "Updating existing variable..."
    Write-Verbose "Existing value: $(if ($isSensitive) { "********" } else { $_.Value })"
    $_.Value = $variableValue
    $_.Type = $variableType
    $_.IsSensitive = $isSensitive
    $_.Scope = Get-OctopusSetting Scope $_.Scope
    $variableExists = $true
}
if (!$variableExists) {
    Write-Host "Creating new variable..."
    $variableSet.Variables += @{
        Name = $StepTemplate_VariableName
        Value = $variableValue
        Type = $variableType
        IsSensitive = $isSensitive
        Scope = (Get-OctopusSetting Scope @{})
    }
}

Write-Host "Saving updated variable set..."
Invoke-OctopusApi $variableSet.Links.Self -Method Put -Body $variableSet | Out-Null

Provided under the Apache License version 2.0.

Report an issue

To use this template in Octopus Deploy, copy the JSON below and paste it into the Library → Step templates → Import dialog.

{
  "Id": "54b22700-3217-48ac-8749-e4a31b424834",
  "Name": "Save Octopus Output Variable",
  "Description": "Saves an [output variable](https://octopus.com/docs/deploying-applications/variables/output-variables) to the given project / library variable set",
  "Version": 5,
  "ExportedAt": "2021-10-21T15:24:33.519Z",
  "ActionType": "Octopus.Script",
  "Author": "harrisonmeister",
  "Parameters": [
    {
      "Id": "41e164af-94b1-42ac-8462-3e1a6ba49bbb",
      "Name": "StepTemplate_ApiKey",
      "Label": "API Key",
      "HelpText": "Provide an Octopus API Key with appropriate permissions to save the variable",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "Sensitive"
      },
      "Links": {}
    },
    {
      "Id": "ceddb0a2-621a-4cce-94e1-42ad1bf4ba72",
      "Name": "StepTemplate_DeploymentStep",
      "Label": "Deployment Step",
      "HelpText": "Select the step with the [output variable](https://octopus.com/docs/deploying-applications/variables/output-variables)",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "StepName"
      },
      "Links": {}
    },
    {
      "Id": "fdd47428-d7ce-4f8d-b73b-e4d513d1aea8",
      "Name": "StepTemplate_VariableName",
      "Label": "Variable Name",
      "HelpText": "Name of the [variable used when it was set](https://octopus.com/docs/deploying-applications/variables/output-variables#Outputvariables-Settingoutputvariablesusingscripts)\n\n_Note: The same name will be given to the saved variable_",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      },
      "Links": {}
    },
    {
      "Id": "7a81c569-063f-41cb-ae61-1c4ebb67293a",
      "Name": "StepTemplate_VariableSetType",
      "Label": "Variable Set Type",
      "HelpText": "If the output variable is being saved to a project or [library variable set](https://octopus.com/docs/deploying-applications/variables/library-variable-sets)",
      "DefaultValue": "project",
      "DisplaySettings": {
        "Octopus.ControlType": "Select",
        "Octopus.SelectOptions": "project|Project Variable\nlibrary|Library Variable Set"
      },
      "Links": {}
    },
    {
      "Id": "09e61027-ab16-4171-80c7-c7656f68833a",
      "Name": "StepTemplate_VariableSetName",
      "Label": "Variable Set Name",
      "HelpText": "Name of the project or [library](https://octopus.com/docs/deploying-applications/variables/library-variable-sets) variable set where the output variable should be saved",
      "DefaultValue": "#{Octopus.Project.Name}",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      },
      "Links": {}
    },
    {
      "Id": "6e3cf177-1dcc-4b7c-9d24-ec7805167cef",
      "Name": "StepTemplate_IsSensitive",
      "Label": "Is Sensitive?",
      "HelpText": "If the variable should be marked as [sensitive](https://octopus.com/docs/deploying-applications/variables/sensitive-variables) and the value masked from logs",
      "DefaultValue": "False",
      "DisplaySettings": {
        "Octopus.ControlType": "Checkbox"
      },
      "Links": {}
    }
  ],
  "Properties": {
    "Octopus.Action.Script.Syntax": "PowerShell",
    "Octopus.Action.Script.ScriptSource": "Inline",
    "Octopus.Action.RunOnServer": "true",
    "Octopus.Action.Script.ScriptBody": "$ErrorActionPreference = 'Stop'\n\n$StepTemplate_BaseUrl = $OctopusParameters['#{if Octopus.Web.ServerUri}Octopus.Web.ServerUri#{else}Octopus.Web.BaseUrl#{/if}'].Trim('/')\nif ([string]::IsNullOrWhiteSpace($StepTemplate_ApiKey)) {\n    throw \"The step parameter 'API Key' was not found. This step requires an API Key to function, please provide one and try again.\"\n}\n\nfunction Invoke-OctopusApi {\n    param(\n        [Parameter(Position = 0, Mandatory)]$Uri,\n        [ValidateSet(\"Get\", \"Put\")]$Method = 'Get',\n        $Body\n    )\n    $requestParameters = @{\n        Uri = ('{0}/{1}' -f $StepTemplate_BaseUrl, $Uri.TrimStart('/'))\n        Method = $Method\n        Headers = @{ \"X-Octopus-ApiKey\" = $StepTemplate_ApiKey }\n        UseBasicParsing = $true\n    }\n    if ($null -ne $Body) { $requestParameters.Add('Body', ($Body | ConvertTo-Json -Depth 10)) }\n    Write-Verbose \"$($Method.ToUpperInvariant()) $($requestParameters.Uri)\"   \n    Invoke-WebRequest @requestParameters | % Content | ConvertFrom-Json | Write-Output\n}\n\nfunction Test-SpacesApi {\n\tWrite-Verbose \"Checking API compatibility\";\n\t$rootDocument = Invoke-OctopusApi 'api/';\n    if($rootDocument.Links -ne $null -and $rootDocument.Links.Spaces -ne $null) {\n    \tWrite-Verbose \"Spaces API found\"\n    \treturn $true;\n    }\n    Write-Verbose \"Pre-spaces API found\"\n    return $false;\n}\n\nif(Test-SpacesApi) {\n\t$spaceId = $OctopusParameters['Octopus.Space.Id'];\n    if([string]::IsNullOrWhiteSpace($spaceId)) {\n        throw \"This step needs to be run in a context that provides a value for the 'Octopus.Space.Id' system variable. In this case, we received a blank value, which isn't expected - please reach out to our support team at https://help.octopus.com if you encounter this error.\";\n    }\n\t$baseApiUrl = \"api/$spaceId\" ;\n} else {\n\t$baseApiUrl = \"api\" ;\n}\n\nfunction Get-OctopusSetting {\n    param([Parameter(Position = 0, Mandatory)][string]$Name, [Parameter(Position = 1, Mandatory)]$DefaultValue)\n    $formattedName = 'Octopus.Action.{0}' -f $Name\n    if ($OctopusParameters.ContainsKey($formattedName)) {\n        $value = $OctopusParameters[$formattedName]\n        if ($DefaultValue -is [bool]) { return ([System.Convert]::ToBoolean($value)) }\n        if ($DefaultValue -is [array] -or $DefaultValue -is [hashtable] -or $DefaultValue -is [pscustomobject]) { return (ConvertFrom-Json -InputObject $value) }\n        return $value\n    }\n    else { return $DefaultValue }\n}\n\n$outputVariableKey = \"Octopus.Action[${StepTemplate_DeploymentStep}].Output.${StepTemplate_VariableName}\"\nif (!$OctopusParameters.ContainsKey($outputVariableKey)) {\n    throw \"Variable '$StepTemplate_VariableName' has not been output from '$StepTemplate_DeploymentStep'\"\n}\n$isSensitive = [System.Convert]::ToBoolean($StepTemplate_IsSensitive)\n$variableType = if ($isSensitive) { \"Sensitive\" } else { \"String\" }\n\n$variableValue = $OctopusParameters[$outputVariableKey]\nWrite-Host \"Name: $StepTemplate_VariableName\"\nWrite-Host \"Type: $variableType\"\nWrite-Host \"Value: $(if ($isSensitive) { \"********\" } else { $variableValue })\"\nWrite-Host ' '\n\nWrite-Host \"Retrieving $StepTemplate_VariableSetType variable set...\"\nif ($StepTemplate_VariableSetType -eq 'project') {\n    $variableSet = Invoke-OctopusApi \"$baseApiUrl/projects/all\" | ? Name -eq $StepTemplate_VariableSetName | % { Invoke-OctopusApi $_.Links.Variables }\n}\nif ($StepTemplate_VariableSetType -eq 'library') {\n    $variableSet = Invoke-OctopusApi \"$baseApiUrl/libraryvariablesets/all?ContentType=Variables\" | ? Name -eq $StepTemplate_VariableSetName | % { Invoke-OctopusApi $_.Links.Variables }\n}\nif ($null -eq $variableSet) {\n    throw \"Unable to find $StepTemplate_VariableSetType variable set '$StepTemplate_VariableSetName'\"\n}\n\n$variableExists = $false\n$variableSet.Variables | ? Name -eq $StepTemplate_VariableName | % {\n    Write-Host \"Updating existing variable...\"\n    Write-Verbose \"Existing value: $(if ($isSensitive) { \"********\" } else { $_.Value })\"\n    $_.Value = $variableValue\n    $_.Type = $variableType\n    $_.IsSensitive = $isSensitive\n    $_.Scope = Get-OctopusSetting Scope $_.Scope\n    $variableExists = $true\n}\nif (!$variableExists) {\n    Write-Host \"Creating new variable...\"\n    $variableSet.Variables += @{\n        Name = $StepTemplate_VariableName\n        Value = $variableValue\n        Type = $variableType\n        IsSensitive = $isSensitive\n        Scope = (Get-OctopusSetting Scope @{})\n    }\n}\n\nWrite-Host \"Saving updated variable set...\"\nInvoke-OctopusApi $variableSet.Links.Self -Method Put -Body $variableSet | Out-Null",
    "Octopus.Action.Script.ScriptFileName": null,
    "Octopus.Action.Package.FeedId": null,
    "Octopus.Action.Package.PackageId": null
  },
  "Category": "Octopus",
  "HistoryUrl": "https://github.com/OctopusDeploy/Library/commits/master/step-templates//opt/buildagent/work/75443764cd38076d/step-templates/save-octopus-output-variable.json",
  "Website": "/step-templates/54b22700-3217-48ac-8749-e4a31b424834",
  "Logo": "iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAMAAACahl6sAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAC1QTFRFT6Tl////L5Pg8vj9Y67omsvwPJrisdfzfbzs5fL7y+T32Ov5isLucLXqvt31CJPHWwAABMJJREFUeNrs3deW4jAMAFDF3U75/89dlp0ZhiU4blJEjvQ8hYubLJsA00UCBCIQgQhEIAIRiEAEIhCBCEQgAhGIQAQiEIEIhD8kJm+t+QprfdKfB9HbYpx6CWfspj8HMi+gMgHL/AmQA8W3JTKH+ALFvzCeL0RbpyoCPE9IJeNOSQwh5Z3qd6yRGWQ2qi2cZQWxqj1WzQYSjeoJmJlAklOd4VlArOqPhQEkqBERToeMcfRJBkC0Uep8CfBpjz4JsHJ0zF3dkEWNje0kiB/sUC6eApndaIiCMyAa1PiwJ0AWhRGJHJJQHG2dC7h1rNbO1QOxSA7lNCkkKrQIpJCAB1GREILYIC1NAiwbpKFJgGWDNExcwGstfExcZBCHC6nOglshHtmhViLIig1RNBCN7qjtW8C0Z1UvJcC1Z9XmwMBzzvobmgAy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Few1/JXtOA0yJCv7ah7X8ObUuT5kObU30+fDZm8+zqP+HTIpK0xQ796b5Kv2hSIQAQiEIEIRCACEYhABCIQgQhEIAIRiEAEIpBf8UeAAQAEjtYmlDTcCgAAAABJRU5ErkJggg==",
  "$Meta": {
    "Type": "ActionTemplate"
  }
}

History

Page updated on Thursday, October 21, 2021