问题
When deploying to a stage within a release pipeline, part of the process currently in place is to tidy up from the previous version deployed on that stage, which means telling the current deployment what the previous deployed version was. This is currently being done manually with a custom variable, but it seems like it should be the sort of thing that can be retrieved from the agent. Given a different number of releases with incremented revisions will occur earlier in the pipeline, the variables being used are per stage, rather than knowing what the previous version was throughout the whole pipeline. Does anyone know if there is a way to retrieve this?
回答1:
There isn't a previous release variable in the predefined Release Variables, however, you should be able to achieve this by querying the Azure DevOps REST API using a PowerShell task from within your pipeline.
Your scripts with run under the security context of the build pipeline. To enable this, the agent phase needs to have the "allow scripts to access the OAuth token" turned on.
The List Deployments endpoint can be used to query all deployments, but it can be filtered to find the successful releases for your release definition and current environment.
Add a PowerShell task with the following script:
param( )
# use this function to invoke the scripts locally with a PAT token
function getAuthToken($user, $accessToken) {
$userString = "{0}:{1}" -f $user, $accessToken
$base64String = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes($userString))
return "Basic {0}" -f $base64String
}
function getOAuthToken() {
return "Bearer {0}" -f $env:SYSTEM_ACCESSTOKEN
}
function getServerUrl() {
return [string]::Format("https://{0}{1}", $env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI, $env:SYSTEM_TEAMPROJECTID)
}
function InvokeRestApi($relativeUri, $authHeader) {
$baseUrl = getServerUrl
$url = [Uri]::EscapeUriString((getServerUrl) + $relativeUri + "?api-version=5.0")
Write-Host "Querying:" $url
return Invoke-WebRequest $url -Headers @{Authorization=($authHeader)} | ConvertFrom-Json
}
$auth = getAuthToken
$url = "/release/deployments?definitionId=" + $env:RELEASE_DEFINITIONID
$url += "&definitionEnvironmentId=" + $env:RELEASE_DEFINITIONENVIRONMENTID
$url += "&deploymentStatus=succeeded"
$url += "&queryOrder=descending"
$json = InvokeRestApi $url $auth
$lastRelease = $json.value[0]
来源:https://stackoverflow.com/questions/57098681/is-there-a-variable-to-find-the-last-successful-deployment-to-a-stage