Download latest artifact from Azure Devops using Powershell - get buildId - powershell

I try to download the latest Artifact from AzureDevops with PowerShell.
Here is my script to get the latest buildid:
$organisation="aaa"
$project="bbb"
$personalAccessToken="ccc"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($personalAccessToken)"))
$headers = #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$url = "https://dev.azure.com/$organisation/$project/_apis/build/latest/1?branchName=main"
$result = Invoke-RestMethod -Uri $url -Method Get -ContentType application/json -Headers $headers
When I execute this, I get the exception
Build pipeline 1 was not found.
Can someone help me, where I can get the correct definitionId?

Download latest artifact from Azure Devops using Powershell - get buildId
To get the latest artifact from the build, we need to provide the parameter definitions and the $top for the REST API Builds - List:
GET https://dev.azure.com/{organization}/{project}/_apis/build/builds?definitions={definitions}&$top={$top}&branchName={branchName}&api-version=6.0
Note: The branch name parameter should include the refs/heads
As test with postman:
And if you want to know the correct definitionId, you could open the pipeline in the web page, it in the URL:

Related

How can I get last successfully deployed build id of specific artifact in YML based deploy pipeline

I want to get last successfully deployed build id of specific artifact, but I didn't get any solution of it.
How can I get last successfully deployed build id of specific artifact in YML based deploy pipeline
You could use the REST API Releases - Get Release:
GET https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases/{releaseId}?api-version=6.1-preview.8
My test Inline powershell task scripts:
$url = "GET https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases/{releaseId}?api-version=6.1-preview.8
"
$ReleasePipeline = Invoke-RestMethod -Uri $url -Headers #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
} -Method Get
$BuildId= $ReleasePipeline.artifacts.definitionReference.version.id
Write-Host This is Build Id: $BuildId
Note: Go to the Agent Phase and select Allow Scripts to Access OAuth Token. See Use the OAuth token to access the REST API

From where I get all publish artifact of all stages of azure build pipeline instead of searching from all stages

I am publishing build artifact of each run over azure pipeline, whatever artifact I have published than can be accessible to that specific stage(run), But my query is in Azure is there any build artifacts repository where we can get all the build artifacts for all the builds of that pipeline ?
To get all the build artifacts for all pipeline runs, you need to combine the following two Rest APIs: Builds - List and Artifacts - List
Here is a PowerShell example:
$token = "PAT"
$url="https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=6.0"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method Get -ContentType application/json
ForEach( $buildid in $response.value.id )
{
echo $buildid
$url1= "https://dev.azure.com/{organization}/{project}/_apis/build/builds/$($buildid)/artifacts?api-version=4.1"
$response1 = Invoke-RestMethod -Uri $url1 -Headers #{Authorization = "Basic $token"} -Method Get -ContentType application/json
echo $response1 | ConvertTo-Json
}
This sample will traverse all pipeline runs and get relevant artifacts information.
Update:
When you use Classic Pipeline, you could add a PowerShell task and input the PowerShell Script. Please change the parameters in the script to make it suitable for your organization

Azure cli: clone pipeline

Looking at az pipelines documentation it seems it's not possible to clone a pipeline using cli.
I've looked at getting the yaml (az pipelines show -name=x > x_orig.yaml) and then trying to change json and create pipeline from modified yaml, but that feels like a lot of work that could break after next update.
Is there a way to clone a pipline without going the the Web UI?
Currently, there indeed is not available Azure CLI that can clone or export/import a pipeline to create a new pipeline.
I also searched and tried the Azure DevOps REST API for Pipelines, but did not find the available API.
Ideally, the Azure CLI "az pipelines create" can provide an input parameter that allows users specify an existing pipeline as a starting point for the new pipeline.
If your projects really need this feature, I recommend that you can directly report a feature request on the "Azure/azure-cli" repository to ask adding the parameter like as above mentioned. That will allow you directly interact with the appropriate engineering team, and make it more convenient for the engineering team to collect and categorize your suggestions.
As a workaround, we could clone the build definition via power shell script to call REST API.
Note: We need to change the original build definition name.
REST API
Get build definition:
GET https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=6.0
Create build definition
POST https://dev.azure.com/{organization}/{project}/_apis/build/definitions?api-version=6.0
Power shell script
$connectionToken="{pat}"
$base64AuthInfo= [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($connectionToken)"))
$BuildDefinitionInfoURL = "https://dev.azure.com/{org name}/{project name}/_apis/build/definitions/386"
$BuildDefinitionInfo = Invoke-RestMethod -Uri $BuildDefinitionInfoURL -Headers #{authorization = "Basic $base64AuthInfo"} -Method Get
Write-Host $BuildDefinitionInfo.name
$BuildDefinitionInfo.name = $BuildDefinitionInfo.name +" clone"
Write-Host $BuildDefinitionInfo.name
$body = $BuildDefinitionInfo | ConvertTo-Json -Depth 99
$createBuildDefinitionURL = "https://dev.azure.com/{org name}/{project name}/_apis/build/definitions?api-version=6.0"
$response = Invoke-RestMethod -Uri $createBuildDefinitionURL -ContentType "application/json" -Body $body -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)} -Method POST
Write-Host $response.id
Result:

Managing branches with Azure DevOps Classic Build Pipelines and TFVC

How do you manage building from branches when using Azure DevOps Classic Build Pipelines and TFVC?
I believe that the only viable option is to copy the build pipeline with a new name and update the source code mapping to point to the new TFVC branch.
I see the ADO web UI provides the option to clone an individual build definition, yet as I have over 200+ build pipelines to clone whenever I branch is there a more efficient way to do this? Or is the only option to write a custom tool to leverage the ADO REST Api?
Since you need to clone pipelines in batches, using scripts to run the Rest API will be a reasonable method. As far as I know, there is no easy way out of the box other than this.
You could try the following PowerShell Script Sample:
$DefinitionIds = "PipelineIDs" #InPut All Pipelineids(e.g. "324,323,xxx" )
$DefinitionId = $DefinitionIds.split(",");
$token = "PAT Token"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
foreach ($i in $DefinitionId)
{
echo $i
$url="https://dev.azure.com/{OrganizationName}/{ProjectName}/_apis/build/definitions/$($i)?api-version=6.0"
$response = Invoke-RestMethod -Uri $url -Headers #{Authorization = "Basic $token"} -Method Get -ContentType application/json
Write-Host "$($response | ConvertTo-Json -Depth 100)"
$response.repository.properties.tfvcMapping= '{"mappings":[{"serverPath":"$/TFVCBranchName","mappingType":"map","localPath":"\\"}]}' # ServerPath is the Branch name
$response.repository.name = "TFVCRepoName" #Repo Source Name
$response.name = "Pipeline $i Clone" # Cloned PipelineName
echo $response.name
$url1= "https://dev.azure.com/{OrganizationName}/{ProjectName}/_apis/build/definitions?api-version=6.0"
$json = #($response) | ConvertTo-Json -Depth 100
$response1 = Invoke-RestMethod -Uri $url1 -Headers #{Authorization = "Basic $token"} -Method Post -Body $json -ContentType application/json
}
Here are the Two Rest APIs used in the Script:
Definitions - Get
Definitions - Create
Result:
The cloned Pipeline will be set to the new TFVC branch and Build definition name.

"Download pipeline artifact" task output

"Download build artifacts" task has the output variable BuildNumber that makes it possible to get the id of the build the artifact was downloaded from. The new "Download pipeline artifact" task (which is preferred over the "Download build artifacts") does not have any the output variables. Is there a way to get the id of the build the artifact was downloaded from?
Also posted an issue on GitHub.
Microsoft is about to release a fix.
There is workaround to get the build id of the downloaded artifact using restful api.
To get the BuildId of the Specific version. You can refer to below below example.
First add a powershell task in your pipeline to run below scripts.
To get the definition id provided definition name(definition id will be used in the following scripts), check here for rest API.
$urldefinition ="https://dev.azure.com/<org>/<proj>/_apis/build/definitions?name=AboutSite-ASP.NET-CI&api-version=5.1"
$result = Invoke-RestMethod -Uri $urldefinition -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"} -Method Get
$definition= $result.value
$definitionId = $definition[0].id
Then you can get the build id with below scripts:
$url="https://dev.azure.com/<org>/<proj>/_apis/build/builds?definitions=$definitionId&buildNumber=20191109AboutSite-ASP.NET-CI&statusFilter=completed&resultFilter=succeeded&api-version=5.1"
$result = Invoke-RestMethod -Uri $urldefinition -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"} -Method Get
$build = $result.value
$id = $build[0].id
And then you can output the buildid for the following task to use with below script:
echo "##vso[task.setvariable variable=ArtifactBuildId;isOutput=true]$id"
To get the latest build id you can simply use below api
GET https://dev.azure.com/{organization}/{project}/_apis/build/latest/{definition}?branchName={branchName}&api-version=5.1-preview.1