How to add a Environment Scope and Deployment Target Scope to a variable in OctopusDeploy

836 Views Asked by At

I have to generate a variable dynamically and set it to the variable list using Octopus Deploy REST API.

I don't know how to set the Environment Scope and Deployment Scope to that variable for different values.

Example - ENV_NAME -> [dev,sit,uat,prod - are values for ENV scope (dev,sit,uat,prod) and roles (x,y,z)] etc

How to set the corresponding values for each scope using Octopus REST API

Below is what I have to set the variable name and values

$variableList = @(
  @{
     Name = "API_ID"
     Value = $api_id
     Type = "String"
     IsSensitive = $false 
  }
)

# Get space
$space = (Invoke-RestMethod -Method Get -Uri "$octopusURL/api/spaces/all" -Headers $header) | Where-Object {$_.Name -eq $spaceName}

# Get project
$project = (Invoke-RestMethod -Method Get -Uri "$octopusURL/api/$($space.Id)/projects/all" -Headers $header) | Where-Object {$_.Name -eq $projectName}

# Get project variables
$projectVariables = Invoke-RestMethod -Method Get -Uri "$octopusURL/api/$($space.Id)/variables/$($project.VariableSetId)" -Headers $header

foreach($variable in $variableList){
  # Check to see if variable is already present
  $variableToUpdate = $projectVariables.Variables | Where-Object {$_.Name -eq $variable.Name}
  if ($null -eq $variableToUpdate)
  {
     # Create new object
     $variableToUpdate = New-Object -TypeName PSObject
     $variableToUpdate | Add-Member -MemberType NoteProperty -Name "Name" -Value $variable.Name
     $variableToUpdate | Add-Member -MemberType NoteProperty -Name "Value" -Value $variable.Value
     $variableToUpdate | Add-Member -MemberType NoteProperty -Name "Type" -Value $variable.Type
     $variableToUpdate | Add-Member -MemberType NoteProperty -Name "IsSensitive" -Value $variable.IsSensitive

     # Add to collection
     $projectVariables.Variables += $variableToUpdate

     $projectVariables.Variables
  }

   # Update the value
   $variableToUpdate.Value = $variable.Value
}   

# Update the collection
Invoke-RestMethod -Method Put -Uri "$octopusURL/api/$($space.Id)/variables/$($project.VariableSetId)" -Headers $header -Body ($projectVariables | ConvertTo-Json -Depth 10)
1

There are 1 best solutions below

0
benPearce On

The OctopusDeploy-Api repo contains many sample scripts.

ModifyOrAddVariableToProject.ps1 does almost exactly what you are attempting to do here.

Two things to note, environment scopes have to be the Id of the environment, not the name as shown here, but roles can just be any string, under the scope type of Roles.

If you are trying to scope a variable to the deployment process, then the scope type is ProcessOwner and the value would be the Project Id, or to scope to a runbook it would be the Runbook Id.