How to download the latest build artifacts from Azure DevOps programmatically?

How to download the latest build artifacts from Azure DevOps programmatically? — VaST ITES INC

To download the latest build artifacts from Azure DevOps programmatically, you can use the Azure DevOps REST API. Here’s a step-by-step guide on how to do this using a script in PowerShell or a similar scripting language.

Step-by-Step Guide

1. Generate a Personal Access Token (PAT)

  • Go to Azure DevOps and navigate to User settings > Personal access tokens.
  • Create a new token with the necessary scopes (Build and Artifacts).
  • Copy the token as you will need it for authentication.

2. Find the Latest Build ID

You need to query the latest build for your project and pipeline.

PowerShell Example

$organization = "your-organization"
$project = "your-project"
$pipelineId = "your-pipeline-id"
$pat = "your-personal-access-token"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($pat)"))
$buildsUrl = "https://dev.azure.com/$organization/$project/_apis/build/builds?definitions=$pipelineId&$top=1&statusFilter=completed&api-version=7.1-preview.5"
$latestBuild = Invoke-RestMethod -Uri $buildsUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}
$buildId = $latestBuild.value[0].id

3. List the Artifacts for the Latest Build

Once you have the buildId, list the artifacts associated with it.

$artifactsUrl = "https://dev.azure.com/$organization/$project/_apis/build/builds/$buildId/artifacts?api-version=7.1-preview.5"
$artifacts = Invoke-RestMethod -Uri $artifactsUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}

4. Download the Artifacts

Loop through the artifacts and download them.

foreach ($artifact in $artifacts.value) {
$artifactName = $artifact.name
$downloadUrl = $artifact.resource.downloadUrl
$outputFile = "$artifactName.zip" # or any desired output path
Invoke-WebRequest -Uri $downloadUrl -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} -OutFile $outputFile
}

5. Optional: Unzip the Artifacts

If the artifact is zipped, you can unzip it using PowerShell.

Expand-Archive -Path $outputFile -DestinationPath "your-destination-folder"

Summary

  • Generate a PAT for Azure DevOps.
  • Find the latest build ID using the Azure DevOps REST API.
  • List and download artifacts from the latest build.
  • Unzip the downloaded files if necessary.

This script can be adjusted to work with other scripting languages (like Python) or automated in CI/CD pipelines.

We are VaST ITES INC, a DevOps consulting services company based in the Canada. We help businesses of all sizes adopt and implement DevOps practices to improve their software development and delivery processes.

Contact us for a free Consultation

Reach out to us now: 🤝
🌐 https://vastites.ca/contact-us/
☎️ +1 3127249560
📩 [email protected]

Learn more How to download the latest build artifacts from Azure DevOps programmatically?

Leave a Reply