Updating the scope of a Variable in a Variable Set

Hi All,

I am trying to add a variable to a variable set which already exists.
The VARIABLE_NAME I am creating already exists in the variable set with NO Scope. (i.e. This is the one I want the projects to use by default. At some point in my steps I want to add a new variable of the same name
I want to keep this VARIABLE_NAME and add another variable with the SAME NAME but a different VALUE and then add the scope to an Environment which has just been created
Ideally this wouldnt fail if re-ran several times

Does anyone have any ideas?!!?

Add-Type -Path 'C:\Program Files\Octopus Deploy\Octopus\Octopus.Client.dll’
Add-Type -Path ‘C:\Program Files\Octopus Deploy\Octopus\Newtonsoft.Json.dll’

$OctopusURL = “http://localhost
$AccountName = “MY_ACCOUNT”
$octopusAPIKey = “MY_API”

#Retrieve Environment object with name $OctopusEnvironmentName - this bit works fine but I have hardcoded the Environment below when testing
$Environments = Invoke-WebRequest $OctopusURL/api/environments -Method Get -Headers $header | ConvertFrom-Json
$EnvironmentObject = $Environments.Items | where {$_.Name -like $AccountName}

$endpoint = New-Object Octopus.Client.OctopusServerEndpoint $OctopusURL, $octopusAPIKey
$repository = New-Object Octopus.Client.OctopusRepository $endpoint

$libraryVariableSet = New-Object Octopus.Client.Model.LibraryVariableSetResource
$libraryVariableSet.Name = “MY_HARDCODED_VARIABLESET_NAME”

$libraryVariableSet = $repository.LibraryVariableSets.Create($libraryVariableSet);

$newVariable = New-Object Octopus.Client.Model.VariableResource
$newVariable.Name = “VARIABLE_NAME”
$newVariable.Value = $AccountName
#if you want to scope your variable
$newVariable.Scope.Add([Octopus.Client.Model.ScopeField]::Environment, (New-Object Octopus.Client.Model.ScopeValue(“MY_ENVIRONMENT”)))

$variableSet = $repository.VariableSets.Get($libraryVariableSet.VariableSetId)


$variableSet = $repository.VariableSets.Modify($variableSet)

Hi Michael,

We have a very similar script of what you want to do in https://github.com/OctopusDeploy/OctopusDeploy-Api/blob/master/Octopus.Client/PowerShell/Variables/UpdateVariableInProject.ps1, that should get you nearly there, all you need to do is remove the if statement and leave the else part so you add a new variable all the time.

Hope this gets you there.


I have this working now but how do you ADD another Environment Scope to a variable that already exists?

Hi Michael,

The script I linked before has a $VariableToModify parameter, that should allow you to update an existing variable, the only issue is that you have multiple values with the same variable name, so in your case you need to find the specific variable that you want to update by matching the name, current value and current scopes.
So you need to modify ?{$_.name -eq $VariableToModify} to also filter on value and scopes.

Hope this make sense.


Managed to get this working, therefore closing