FlowSoft.DevOps.psm1

Function Add-EnvironmentPieplineVariable {
    param
    ( 
        [Parameter(Mandatory = $true)]
        [string] $PieplineName,
        [Parameter(Mandatory = $true)]
        [string] $EnvironmentName,
        [Parameter(Mandatory = $true)]
        [string] $VariableValue,
        [Parameter(Mandatory = $true)]
        [string] $VariableKey
    )
   
    Write-Host "ensure release definition variable $VariableKey"
    $apiUrl = "$($env:SYSTEM_TEAMFOUNDATIONSERVERURI)/$($env:SYSTEM_TEAMPROJECTID)/_apis"
    $url = "$apiUrl/release/definitions?api-version=5.1"

    $body = Invoke-RestMethod -Method GET -Uri $url -Headers @{
        Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
    }
    $definitionId = (($body.value | Where-Object { $_.name -eq $PieplineName } | Select-Object -First 1).Id)
    $definitionId = "$definitionId"

    $url = "$apiUrl/release/definitions/$($definitionId)?api-version=5.1"

    $body = Invoke-RestMethod -Method GET -Uri $url -Headers @{
        Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
    }

    $environment = $body.environments | Where-Object { $_.name -eq "$EnvironmentName" } | Select-Object -First 1

    if ($null -eq $environment.variables.$VariableKey) {
        Write-Output "add variable: $VariableKey"
        $environment.variables | Add-Member -NotePropertyName $VariableKey -NotePropertyValue $VariableValue
    }

    $environment.variables.$VariableKey = [PSCustomObject]@{value = "$VariableValue" }
    $body = ($body | ConvertTo-Json -Depth 100)
    Invoke-RestMethod -Uri $url -Method Put -Body $body -ContentType "application/json" -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN" } | Out-Null
}