Skip to content

Instantly share code, notes, and snippets.

@kevinhillinger
Last active January 29, 2020 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinhillinger/f5faaf0421f251b2660e0a66861b5821 to your computer and use it in GitHub Desktop.
Save kevinhillinger/f5faaf0421f251b2660e0a66861b5821 to your computer and use it in GitHub Desktop.
Azure DevOps REST API usage from Azure DevOps
# Setting the script to authenticate using the system access token on the Azure DevOps Build Agent
# Set the agent job to "Allow scripts to access OAuth token" in the build
$pat = "Bearer $env:System_AccessToken"
# this will be the correlation value used to collect all the builds
$sourceVersion = $env:BUILD_SOURCEVERSION
Write-Output ("##vso[task.setvariable variable=sourceVersion;]$sourceVersion")
$organizationName = ([System.Uri]$env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI).Host.split('.')[0]
$baseUrl = "https://dev.azure.com/$organizationName/$env:SYSTEM_TEAMPROJECTID"
# build reason filter. Use 'pullRequest' to further refine if possible
$reasonFilter = 'all'
$buildsUrl = "$baseUrl/_apis/build/builds?queryOrder=startTimeDescending&reasonFilter=$reasonFilter&statusFilter=all&properties=id,sourceBranch,sourceVersion&`$top=10&api-version=5.1"
Write-Output "builds url: $buildsUrl"
$data = Invoke-RestMethod -Uri "$buildsUrl" -Headers @{Authorization = $pat}
if ($env:SYSTEM_DEBUG -eq $true) {
Write-Output "Response: $($data.count)"
ConvertTo-Json $data.value
}
# get all the build Ids
$buildIds = $ids = $($data.value | Where-Object { ($_.sourceVersion -eq $sourceVersion) -and ($_.id -ne $env:BUILD_BUILDID) } | Select-Object -ExpandProperty id)
$buildIdsFilter = $buildIds -join ","
if ([boolean]$env:SYSTEM_DEBUG) {
Write-Output "Build IDs:"
$buildIdsFilter
}
Write-Output ("##vso[task.setvariable variable=buildIds;]$buildIdsFilter")
# use the list of ids to then perform a filter status of completed. Once the number of builds return to match the count in buildIds, we can continue
$wereThereAnyFailures = $false
$areAllBuildsInStatusComplete = $false
$pollingInterval = 10
$maxRetries = 5
$retryCount = 0
while ($areAllBuildsInStatusComplete -eq $false) {
$buildsUrl = "$baseUrl/_apis/build/builds?buildIds=$buildIdsFilter&api-version=5.1"
$data = Invoke-RestMethod -Uri "$buildsUrl" -Headers @{Authorization = $pat}
# if any of the builds failed, we have to stop
foreach($build in $data.value) {
if (($build.status -eq 'failed') -or ($build.status -eq 'cancelled')) {
Write-Output "Build $($build.id) failed or was cancelled."
$wereThereAnyFailures = $true
break
}
}
# if all builds completed, we're good
$areAllBuildsInStatusComplete = ($buildIds.Count -eq $($data.value | Where-Object { $_.status -eq 'completed' } ).Count)
if ($areAllBuildsInStatusComplete) {
Write-Output "All builds are completed."
break
}
if ($retryCount -eq $maxRetries) {
Write-Output "Max retry count reached. Cancelling"
break
}
Start-Sleep -s $pollingInterval
$retryCount += 1
}
if ($wereThereAnyFailures) {
Write-Output "there was one or more builds that failed. Cannot proceed with release."
exit 1
}
$pat = "Bearer $env:System_AccessToken"
$organizationName = ([System.Uri]$env:SYSTEM_TEAMFOUNDATIONCOLLECTIONURI).Host.split('.')[0]
$projectName = "$($env:SYSTEM_TEAMPROJECTID)"
# this is a build variable you will need to create as releaseDefinitionId
$releaseDefinitionId = "$($env:releaseDefinitionId)"
$baseUrl = "https://dev.azure.com/$organizationName/$projectName"
$uri = "https://dev.azure.com/$organizationName/$projectName/_apis/release/releases?api-version=5.1"
$body = @{
"definitionId" = $releaseDefinitionId;
"description" = "Creating Sample release";
"artifacts" = @(
@{
"alias": "Fabrikam.CI",
"instanceReference": {
"id" = "2";
"name" = $null;
}
}
);
"isDraft" = $false;
"reason" = "continuousIntegration";
"manualEnvironments" = $null;
}
# Invoke the REST call and capture the results
$result = Invoke-RestMethod -Uri $uri -Method POST -ContentType "application/json" -Body $body -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
# This call should only provide a single result
if ($result.count -eq 0)
{
throw "Unable to locate Release Definition for the Id $($releaseDefinitionId)"
}
$releaseId = $result.value[0].id
Write-Output "Release $releaseId created."
@kevinhillinger
Copy link
Author

Required setup

Build agent settings

Allow scripts to access the OAuth token

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment