FlowSoft.DevOps.psm1

Function Add-EnvironmentPieplineVariable {
    param
    (
        [Parameter(Mandatory = $true)]
        $VariableValue,
        [Parameter(Mandatory = $true)]
        [string] $VariableKey
    )
    Write-Host "ensure Variable $VariableKey"
    $apiUrl = "$($env:SYSTEM_TEAMFOUNDATIONSERVERURI)/$($env:SYSTEM_TEAMPROJECTID)/_apis"
    
    $releaseDefinitionUrl = "$apiUrl/release/definitions/$($env:RELEASE_DEFINITIONID)?api-version=5.1"
    Write-Host "URL: $releaseDefinitionUrl"
    
    $definition = Invoke-RestMethod -Method GET -Uri $releaseDefinitionUrl -Headers @{
        Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
    }
    
    $environment = $definition.environments | Where-Object { $_.Id -eq $env:RELEASE_DEFINITIONENVIRONMENTID }
    if ($null -eq $environment.variables.$VariableKey) {
        Write-Output "add variable: $VariableKey"
        $environment.variables | Add-Member -NotePropertyName $VariableKey -NotePropertyValue "test"
    }
    $environment.variables.$VariableKey = [PSCustomObject]@{value = "$VariableValue" }
    
    $json = $definition | ConvertTo-Json -Depth 100
    Invoke-RestMethod -Uri $releaseDefinitionUrl -Method Put -Body $json -ContentType "application/json" -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN" } |Out-Null

    $releaseUrl = "$apiUrl/release/releases/$($env:RELEASE_RELEASEID)?api-version=5.1"
    Write-Host "URL: $releaseUrl"

    $release = Invoke-RestMethod -Uri $releaseurl -Headers @{
        Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
    }


    $environment = $release.environments | Where-Object { $_.Id -eq $env:RELEASE_DEFINITIONENVIRONMENTID }
    if ($null -eq $environment.variables.$VariableKey) {
        Write-Output "add variable: $VariableKey"
        $environment.variables | Add-Member -NotePropertyName $VariableKey -NotePropertyValue "test"
    }
    $environment.variables.$VariableKey = [PSCustomObject]@{value = "$VariableValue" }

    $json = $release | ConvertTo-Json -Depth 100
    Invoke-RestMethod -Uri $releaseurl -Method Put -Body $json -ContentType "application/json" -Headers @{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN" } |Out-Null
}