Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A code fragment that can be used in an Azure DevOps PowerShell task to find the approver of the current stage of a multi stage YAML pipeline
try {
# this block is in its own try/catch as it uses undocumented API calls, so will fail safe
# we need to stage ID which is only available via a REST call
$uri = "$(System.CollectionUri)/$(System.TeamProject)/_apis/build/builds/$(Build.BuildID)/timeline?api-version=6.0"
$response = Get-WebClient.DownloadString($uri) | ConvertFrom-Json
$stage = $response.records | where-object -property name -eq "$(System.StageName)"
# now we can get the approval, we have to use a new webclient instance else you get a 400 Bad Request error
$uri = "$(System.CollectionUri)_apis/Contribution/HierarchyQuery/project/$(System.TeamProject)?api-version=6.1-preview.1"
$payload = "{`"contributionIds`":[`"ms.vss-build-web.checks-panel-data-provider`"],`"dataProviderContext`":{`"properties`":{`"buildId`":`"$(Build.BuildID)`",`"stageIds`":`"$($stage.id)`",`"checkListItemType`":1,`"sourcePage`":{`"url`":`"$(System.CollectionUri)/$(System.TeamProject)/_build/results?buildId=$(Build.BuildID)&view=results`",`"routeId`":`"ms.vss-build-web.ci-results-hub-route`",`"routeValues`":{`"project`":`"$(System.TeamProject)`",`"viewname`":`"build-results`",`"controller`":`"ContributedPage`",`"action`":`"Execute`"}}}}}"
$response = Get-WebClient.UploadString($uri,"POST", $payload) | ConvertFrom-Json
# to get here someone must have done the approval and allowed the stage to be run, so we don't need to null check
$approverEmail = $response.dataProviders."ms.vss-build-web.checks-panel-data-provider".approvals.steps.actualApprover.uniqueName
} catch {
write-warning ("Cannot find the approver: " + $_)
$approverEmail = "Cannot access approver"
}
write-host "The environment approver was $approverEmail"
function Get-WebClient {
$webclient = new-object System.Net.WebClient
$webclient.Encoding = [System.Text.Encoding]::UTF8
$webclient.Headers["Content-Type"] = "application/json"
$webclient.Headers["Authorization"] = "Bearer $(System.AccessToken)"
return $webclient
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment