How to delete variable in azure devops release through powershell - azure-devops

I have azure DevOps release and I would like to delete release variables post one stage of deployment. could you please provide some pointers on how to do this? I know how to update the value of the variable using API but am unable to delete the variable. Any pointers are highly appreciated

To delete the release pipeline variable during the release process, you could use the Definitions - Update Rest API.
Here is the PowerShell example:
$url = "$($env:SYSTEM_TEAMFOUNDATIONSERVERURI)$env:SYSTEM_TEAMPROJECTID/_apis/Release/definitions/$($env:RELEASE_DEFINITIONID)?api-version=5.0-preview.3"
Write-Host "URL: $url"
$pipeline = Invoke-RestMethod -Uri $url -Headers #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
$pipeline.variables.PSObject.Properties.Remove('variablename')
####****************** update the modified object **************************
$json = #($pipeline) | ConvertTo-Json -Depth 99
$updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
write-host "=========================================================="
Write-host "The value of Varialbe 'test' is deleted"
write-host "=========================================================="
The following code is used to delete the variable.
$pipeline.variables.PSObject.Properties.Remove('variablename')
For more detailed info, you could refer to this ticket: How to modify Azure DevOps release definition variable from a release task?

Related

Powershell script Trigger an release pipeline using Devops API

I am trying to create a Powershell script create a new release using DevOps API.
I can see the pipeline information using invoke rest method but not able to trigger a pipeline. Can I get some assistance here.?
Thanks,
Venkatraman
It's not documented very well, but to start the release you have to update the status to inProgress.
$updateReleaseUri = "$($vrsmBaseUri)_apis/Release/releases/$($releaseId)/environments/$($environmentId)?api-version=6.0-preview"
$updateReleaseJsonBody = #{status = 'inProgress' }
$updateReleaseJsonBody = $updateReleaseJsonBody | ConvertTo-Json -Depth 100
Invoke-RestMethod -Uri $updateReleaseUri -Method Patch -Headers $headers -Body $updateReleaseJsonBody -ContentType 'application/json'
Ref: https://learn.microsoft.com/en-us/rest/api/azure/devops/release/releases/update-release-environment?view=azure-devops-rest-6.0
You can use the specific endpoint "Releases - Create" to trigger the release pipeline.
The required parameter you need to provide at least to this endpoint is the definitionId of the release pipeline that you want to trigger.
Below is the complete PowerShell script of a demo as reference. I have tested with this script, and it can work well as expected.
$pat = '{Personal Access Token}'
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $pat)))
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", ("Basic {0}" -f $base64AuthInfo))
$headers.Add("Content-Type", "application/json")
$uri = "https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/releases?api-version=6.0"
$body = '{ "definitionId": {definitionId} }'
Invoke-RestMethod -Uri $uri -Headers $headers -Body $body -Method POST | ConvertTo-Json -Depth 10

Update Azure Devops Build Pipeline Variable with Rest API

I have an Azure Devops YAML based Build (Not Release) Pipeline. I have defined a variable called Department. My Requirement is that this variable to be updated at the end of the build using the rest API. I'm using this code.
How to modify Azure DevOps release definition variable from a release task?
The API call works fine. But I'm not sure whether this is the correct API to call. The Department will change for each build. According to the output HTTP method put is not supported.
Note: I have actually defined 5 variables including Department, Department being the last one. When the API is called it only outputs first 3 variables only.
$Department = getDepartment.ps1
$url = "https://dev.azure.com/xxx/xxx/_apis/pipelines/$(System.DefinitionId)/runs?api-version=6.0-preview.1"
$pipeline = Invoke-RestMethod -Uri $url -Headers #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
$pipeline.variables.Department.value = $Department
$json = #($pipeline) | ConvertTo-Json -Depth 99
$updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
Write-host "=========================================================="
Write-host "The value of Variable 'Department' is updated to $( $updatedef.variables.Department.value)"
write-host "=========================================================="
The Department will change for each build. According to the output HTTP method put is not supported.
According to the document Pipelines:
It does not provide a method for update pipeline with PUT.
To resolve this issue, you still need use the REST API Build Definitions - Update:
PUT https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=6.0
The code sample:
$url = "https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=6.0"
Write-Host "URL: $url"
$pipeline = Invoke-RestMethod -Uri $url -Headers #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
$pipeline.variables.Test.value = "$Department"
####****************** update the modified object **************************
$json = #($pipeline) | ConvertTo-Json -Depth 99
$updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
write-host "=========================================================="
Write-host "The value of Varialbe 'Test' is updated to" $updatedef.variables.Test.value
The test result:
When you start the pipeline using the API, you can add the values of the parameters that should be different from the default values, to the payload of the call. So you're not updating the definition, but just the value of the variables for that instance of the pipeline run.
Payload
$JSON = #"
{
"definition": {
"id":"207"
},
"parameters": "{ \"ENVIRONMENT\":\"$($config.testEnvironmentName)\", \"API_CLIENT_SECRET\":\"$($config.testEnvironmentApiClientSecret)\" }"
}
"#
Note that the 'parameters' property has a value as an escaped json string.
This is the API that I use to start the pipeline.
/_apis/build/builds?api-version=7.1-preview
Use a 'POST' method and send the json as the body of the request (content-type application/json).

Set Azure devops Release pipeline variable using REST API

I am able to update the variable in the build pipeline using the below json body
$body = '
{
"definition": {
"id": 25
},
"parameters": "{\"var\":\"value\"}"
}
'
The same json is not working with Release pipeline . Is there any way to pass the variable through same way through release pipeline
Set Azure devops Release pipeline variable using REST API
We could use the REST API Definitions - Get to get all the info about this definition in the body, then we could update the body and use the (Definitions - Update) to update the value of the release definition variable from a release pipeline:
PUT https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/definitions/{definitionId}?api-version=5.0
Following is my test inline powershell scripts:
$url = "https://vsrm.dev.azure.com/{organization}/{project}/_apis/release/definitions/{definitionId}?api-version=5.1"
Write-Host "URL: $url"
$pipeline = Invoke-RestMethod -Uri $url -Method Get -Headers #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
# Update an existing variable named TestVar to its new value 2
$pipeline.variables.TestVar.value = "789"
####****************** update the modified object **************************
$json = #($pipeline) | ConvertTo-Json -Depth 99
$updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
write-host "=========================================================="
Write-host "The value of Varialbe 'TestVar' is updated to" $updatedef.variables.TestVar.value
As test result, the variable TestVar updated to 789:
Update:
But I want to achieve it without updating\changing the definition
The answer is yes. You could use the Releases - Create with request body:
{
"definitionId": Id,
"environments": [
{
"variables": {
"TestVar": {
"value": "xxxx"
},
"TestVar2": {
"value": "xxxx"
}
},
}
],
}
For more information refer the post here.
Hope this helps.
Old topic, but there is a better way now and I believe it deserves a new answer (maybe it was even available since the very beginning, don't know.)
Instead of updating the very definition of the pipeline which only works for future releases, you can now update the currently running release only and that solves your problem.
This is how I set up the tasks in the pipeline:
And here's a snippet from the Powershell task:
(it updates delay_minutes release variable based on deploy_time variable which specifies time in HH:mm format)
if(!"$(deploy_time)") {
Write-Host "deploy_time empty, won't delay deployment"
return
}
$url = "$(System.TeamFoundationServerUri)/$(System.TeamProjectId)/_apis/release/releases/$(Release.ReleaseId)?api-version=5.0"
# Uncomment for debugging
# Write-Host "URL: $url"
$delayMinutes = [int](New-TimeSpan -start (Get-Date) -end "$(deploy_time)").TotalMinutes
if($delayMinutes -lt 0) { $delayMinutes = 0 }
$pipeline = Invoke-RestMethod -Uri $url -Method Get -Headers #{
Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
}
# Uncomment for debugging
# Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
$pipeline.variables.delay_minutes.value = $delayMinutes
$json = #($pipeline) | ConvertTo-Json -Depth 99
$updatedef = Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -Headers #{Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"}
The URL in the snippet uses only always available predefined variables so it should be 100% copy-pastable.
Also make sure to set this on the first agent job:
So that the SYSTEM_TOKEN variable is available in the script.

How to check if a previous release has been completed before deploying a new release

As part of our release pipeline we have a task (the last task) to merge the release branch back to master.
I was wondering whether there is a way to check that this task or the previous release has completed before allowing the new release to be queued. Can a gate be used for this?
Ideally, the release manager would then be able to decide whether they want to continue with the release or to cancel.
You can't use the Invoke Rest API gate with an Azure DevOps API url because for checking the last release status you need to check the environment (stage) status, and for this, you need to the release id (so you can't know what it will be and put it in the rest API gate URL).
But, you can use PowerShell to check the last release and if it is not succeeded just fail the stage.
Add a PowerShell task in your release to check the last release:
$headers = #{ Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN" }
# Replace {org} with your organization
# Replace {project} with your project
# Replace {defId} with your release definition id
$url = "https://vsrm.dev.azure.com/{org}/{project}/_apis/release/releases?definitionId={defId}&api-version=5.1"
$releases = Invoke-RestMethod -Method Get -Uri $url -Headers $headers -ContentType 'application/json'
$releaseUrl = "https://vsrm.dev.azure.com/{org}/{project}/_apis/release/releases/$($releases.value[1].id)?api-version=5.1"
$releaseInfo = Invoke-RestMethod -Method Get -Uri $releaseUrl -Headers $headers -ContentType 'application/json'
$releaseEvnriomentId = $releaseInfo.environments.Where({ $_.name -eq 'THE STAGE NAME WHERE YOU DO MERGE' }).id
$envUrl = "https://vsrm.dev.azure.com/{org}/{project}/_apis/Release/releases/$($releases.value[1].id)/environments/$($releaseEvnriomentId)?api-version=5.1-preview.1"
$environment = Invoke-RestMethod -Method Get -Uri $envUrl -Headers $headers -ContentType 'application/json'
$envStatus = $environment.status
if($envStatus -ne "succeeded")
{
Write-Error "Previous release not succeeded!"
}
else
{
Write-Host "Previous release succeeded :)"
}
In the agent job options you need to allow scripts to access the OAuth token:
Azure functions also support PowerShell so you do it also with Azure functions gate:
1) Create a new Azure Function with VS Code like explained here.
2) In your run.ps1 file replace the code to this code:
using namespace System.Net
# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)
# Write to the Azure Functions log stream.
Write-Host "PowerShell HTTP trigger function processed a request."
$defnitionId = $Request.Query.DefinitionId
# Generate PAT and put it in the {YOUR PAT}
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,"{YOUR PAT}")))
$headers = #{Authorization=("Basic {0}" -f $base64AuthInfo)}
# Replace {org} with your organization
# Replace {project} with your project
$url = "https://vsrm.dev.azure.com/{org}/{project}/_apis/release/releases?definitionId=$($defnitionId)&api-version=5.1"
$releases = Invoke-RestMethod -Method Get -Uri $url -Headers $headers -ContentType 'application/json'
Write-Debug $releases
$releaseUrl = "https://vsrm.dev.azure.com/{org}/{project}/_apis/release/releases/$($releases.value[1].id)?api-version=5.1"
$releaseInfo = Invoke-RestMethod -Method Get -Uri $releaseUrl -Headers $headers -ContentType 'application/json'
Write-Debug $releaseInfo
$releaseEvnriomentId = $releaseInfo.environments.Where({ $_.name -eq 'THE STAGE NAME WHERE YOU DO MERGE' }).id
$envUrl = "https://vsrm.dev.azure.com/{org}/{project}/_apis/Release/releases/$($releases.value[1].id)/environments/$($releaseEvnriomentId)?api-version=5.1-preview.1"
$environment = Invoke-RestMethod -Method Get -Uri $envUrl -Headers $headers -ContentType 'application/json'
Write-Debug $environment
$envStatus = $environment.status
Write-Debug $envStatus
if($envStatus -ne "succeeded")
{
$status = [HttpStatusCode]::BadRequest
$body = "failed"
}
else
{
$status = [HttpStatusCode]::OK
$body = "success"
}
# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]#{
StatusCode = $status
Body = $body
})
3) Publish the function to Azure.
4) Create an Invoke Azure Function gate in your release:
Another option, take the above code, convert him to C# or another language ans use Rest API, deploy to it web server and use the Invoke Rest API gate.

Build pipeline does not delete

In the Azure DevOps portal, I select a pipeline, then the [...] menu, then Delete.
I see a message asking:
Are you sure? This action cannot be undone. This will permanently
delete the pipeline 'vt3e (1)'. Deletion includes all builds and
associated artifacts.
I type in the pipeline name and click OK but the pipeline does not delete.
I have waited some hours.
[Update]
F12 in Chrome shows an error in the console:
ms.vss-build-web.common-library.__y__CePsj5f5zdcIK.min.js:18 Error:
One or more builds associated with the requested pipeline(s) are
retained by a release. The pipeline(s) and builds will not be deleted
[Update]
I am trying to follow the answer given by David D, but when I go to delete a release I get a message
VS402946: 'Release-8' cannot be deleted as it is currently deployed on
stage(s) Stage 1.
[update]
The issue is logged at Microsoft
If you have deleted the release in question, but you still get this error, the solve for it is:
Go to the build pipeline in question.
Under the 'Runs' tab, open each "run" individually
If a run is being retained, you'll see a white box at the top with verbiage like "This run has been retained forever by 82 (Pipeline)" and to right, you'll see a button "View Retention Releases". That's where you'll delete the one or more retention releases.
You'll have to go through each "run" and repeat this process
If that white box/button isn't visible, that particular run isn't retained. You can confirm so by clicking the three dots in the top right corner and selecting "view retention releases"
I was having the same problem and tried different browsers, platforms etc. I found that by removing each release manually under the releases tab, going back to build and then trying to delete the pipeline again worked for me.
I came on the same problem last week and I updated a script from someone to work with the 5.1 API. This script will run over all builds that are retained by a release pipeline. You will need some tweaking of you don't want that all your builds are removed from releases.
$tfsServerURL = "https://dev.azure.com/{organisation}"
$TFSProject = "{project}"
$AzureDevOpsPAT = "{token}"
$AzureDevOpsAuthenicationHeader = #{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(":$($AzureDevOpsPAT)"))}
#Set to $true to update builds by settingretainingByRelease= false
$CorrectError = $true
$URL = "$($tfsServerURL)/$($TFSProject)"
Write-Output $URL
#Get all builddefinitions in Project
$Buildefinitions = (Invoke-RestMethod -Uri ($URL + '/_apis/build/definitions?api-version=5.1') -Method GET -UseDefaultCredentials -Headers $AzureDevOpsAuthenicationHeader).value
foreach($Builddefiniton in $Buildefinitions)
{
Write-Output "Searching in $($Builddefiniton.name) with id $($Builddefiniton.id)"
#Get Builds with keepforever = false and retainedByRelease = true
$Builds = (Invoke-RestMethod -Uri ($URL + '/_apis/build/builds?definitions=' + $Builddefiniton.id + '&api-version=5.1') -Method GET -UseDefaultCredentials -Headers $AzureDevOpsAuthenicationHeader).value | where {$_.keepForever -eq $False -and $_.retainedByRelease -eq $true}
#Get releases linked to the build
foreach ($build in $Builds)
{
If ($CorrectError)
{
Invoke-RestMethod -Uri ($URL + '/_apis/build/builds/'+ $build.id + '?api-version=5.1') -Method Patch -Body (ConvertTo-Json #{"retainedByRelease"='false'}) -UseDefaultCredentials -Headers $AzureDevOpsAuthenicationHeader -ContentType "application/json" | Out-Null
Write-Output "`tFixed"
}
}
}
The PowerShell script will first fetch all build pipelines, then fetch all builds that are not kept infinitely and are retained by a release. If the CorrectError is set to true the script will then try to switch the retainedByRelease flag to false.
After I ran this script I was able to remove my build pipeline.
enter image description hereenter image description hereI have facing same below issue
One or more builds associated with the requested pipeline(s) are retained by a release. The pipeline(s) and builds will not be deleted.
It is simple to solve this, just open the pipeline which you want to delete and if you have seen this in your pipeline just click on three dots [View Retention leases]and open the View retention leases and click on Remove all option and close the pop-up.[Run retention]. Once you perform this action you're now free to go and delete the pipeline which you want.
February 2022 Version of Script to delete a Build Pipeline including all Builds and Leases:
#Azure DevOps Personal Access Token
# https://learn.microsoft.com/en-us/azure/devops/organizations/accounts/use-personal-access-tokens-to-authenticate?view=azure-devops&tabs=Windows
$personalAccessToken = "<Enter your personal access token here>"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($personalAccessToken)"))
$header = #{authorization = "Basic $token"}
$organization = "<Enter your Azure DevOps Organization here>"
$project = "<Enter your Project Name here>"
$pipelineName = "<Enter the Build Pipeline Definition Name to be deleted here>"
#Get all build definitions
# API: GET https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=6.0
$url = "https://dev.azure.com/$organization/$project/_apis/build/definitions?api-version=6.0"
$allBuildDefinitions = Invoke-RestMethod -Uri $url -Method Get -ContentType "application/json" -Headers $header
$allBuildDefinitions.value | Where-Object {$_.name -eq $pipelineName} | ForEach-Object {
Write-Host $_.id $_.name $_.queueStatus
# For debugging reasons, just to be sure that we don't delete the wrong build pipeline
if ( $_.name -ne $pipelineName ) {
return;
}
#Get all Builds for a Definition
# API: GET https://dev.azure.com/{organization}/{project}/_apis/build/builds?definitions={definitions}&queues={queues}&buildNumber={buildNumber}&minTime={minTime}&maxTime={maxTime}&requestedFor={requestedFor}&reasonFilter={reasonFilter}&statusFilter={statusFilter}&resultFilter={resultFilter}&tagFilters={tagFilters}&properties={properties}&$top={$top}&continuationToken={continuationToken}&maxBuildsPerDefinition={maxBuildsPerDefinition}&deletedFilter={deletedFilter}&queryOrder={queryOrder}&branchName={branchName}&buildIds={buildIds}&repositoryId={repositoryId}&repositoryType={repositoryType}&api-version=6.0
$url = "https://dev.azure.com/$organization/$project/_apis/build/builds?definitions=" + $_.id + "&api-version=6.0"
$allBuildsOfDefinition = Invoke-RestMethod -Uri $url -Method Get -ContentType "application/json" -Headers $header
#Process each Build of Definition
$allBuildsOfDefinition.value | Where-Object {$_.retainedByRelease -eq "True"} | Sort-Object id | ForEach-Object {
#Report on retain status
Write-Host "Build Id:" $_.id " retainedByRelease:" $_.retainedByRelease
#Get all Retention Leases for this Build
# API: GET https://dev.azure.com/{organization}/{project}/_apis/build/builds/{buildId}/leases?api-version=7.1-preview.1
$url = "https://dev.azure.com/$organization/$project/_apis/build/builds/" + $_.id + "/leases?api-version=7.1-preview.1"
$allLeasesOfBuild = Invoke-RestMethod -Uri $url -Method Get -ContentType "application/json" -Headers $header
#Delete each Lease of Build
$allLeasesOfBuild.value | ForEach-Object {
#Delete Lease
# API: DELETE https://dev.azure.com/{organization}/{project}/_apis/build/retention/leases?ids={ids}&api-version=7.1-preview.2
$url = "https://dev.azure.com/$organization/$project/_apis/build/retention/leases?ids=" + $_.leaseId + "&api-version=7.1-preview.2"
Invoke-RestMethod -Uri $url -Method Delete -ContentType "application/json" -Headers $header
#Report on Lease deleted
Write-Host "Lease Id:" $_.leaseId " deleted"
}
#Delete Build
# API: DELETE https://dev.azure.com/{organization}/{project}/_apis/build/builds/{buildId}?api-version=7.1-preview.7
$url = "https://dev.azure.com/$organization/$project/_apis/build/builds/" + $_.id + "?api-version=7.1-preview.7"
Invoke-RestMethod -Uri $url -Method Delete -ContentType "application/json" -Headers $header
#Report on Build deleted
Write-Host "Build Id:" $_.id " deleted"
}
#Delete the Build Definition
# API: DELETE https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=6.0
$url = "https://dev.azure.com/$organization/$project/_apis/build/definitions/" + $_.id + "?api-version=6.0"
Invoke-RestMethod -Uri $url -Method Delete -ContentType "application/json" -Headers $header
Write-Host "Build Definition:" $pipelineName " (" $_.id ") deleted"
}
Write-Host "Habe fertig!"
I get the same error if I try to delete a pipeline:
One or more builds associated with the requested pipeline(s) are retained by a release. The pipeline(s) and builds will not be deleted.
On the pipelines page go to the Runs tab, should see a list of records. If you click on the three dots to the right of the row you should see an option to View retention leases. If you Remove All you should then be able to remove that row. You will then need to repeat this step for every row in the the runs tab until all runs have been deleted.
Only then will you be able to delete the parent pipeline.
Microsoft now has an api to delete leases directly.
DELETE https://dev.azure.com/{organization}/{project}/_apis/build/retention/leases?ids={ids}&api-version=6.0-preview.1
https://learn.microsoft.com/en-us/rest/api/azure/devops/build/leases/delete?view=azure-devops-rest-6.0
How to:
Enumerate build definitions
Delete leases for each desired build definition
Delete the build definition
Example:
$organization = "flintsones"
$project = "feed-dino"
$personalAccessToken = "****************"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($personalAccessToken)"))
$header = #{authorization = "Basic $token"}
function DeleteLease($definitionId) {
$url = "https://dev.azure.com/$organization/$project/_apis/build/retention/leases?api-version=6.0-preview.1&definitionId=$definitionId"
$leases = (Invoke-RestMethod -Method GET -Uri $url -ContentType "application/json" -Headers $header )
foreach ($lease in $leases.value) {
$leaseId = $lease.leaseId
$url = "https://dev.azure.com/$organization/$project/_apis/build/retention/leases?ids=$($leaseId)&api-version=6.0-preview.1"
$ignore = Invoke-RestMethod -Method DELETE -Uri $url -ContentType "application/json" -Headers $header
}
}
$url = "https://dev.azure.com/$organization/$project/_apis/build/definitions?api-version=3.2"
Write-Host $url
$buildDefinitions = Invoke-RestMethod -Uri $url -Method Get -ContentType "application/json" -Headers $header
foreach ($def in $builddefinitions.value) {
Write-Host $def.id $def.queueStatus $def.name
DeleteLease $def.id
}
Go to pipeline runs and click on 3 dots when you hover across each run. You will see an option for view retention leases. Click on that and then click on remove all.
You have to do it for all the runs.
Once deleted then try to delete the build pipeline.
I used powershell to delete just my own build (instead of looping through all the build definitions)
$organization = "YourOrganization"
$project = "YourProject"
$personalAccessToken = "GetTokenFromAzureDevops"
$token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($personalAccessToken)"))
$header = #{authorization = "Basic $token"}
$url = "https://dev.azure.com/$organization/$project/_apis/build/definitions?api-version=3.2"
Write-Host $url
$buildDefinitions = Invoke-RestMethod -Uri $url -Method Get -ContentType "application/json" -Headers $header
function DeleteLease($definitionId) {
$url = "https://dev.azure.com/$organization/$project/_apis/build/retention/leases?api-version=6.0-preview.1&definitionId=$definitionId"
$leases = (Invoke-RestMethod -Method GET -Uri $url -ContentType "application/json" -Headers $header )
foreach ($lease in $leases.value) {
$leaseId = $lease.leaseId
$url = "https://dev.azure.com/$organization/$project/_apis/build/retention/leases?ids=$($leaseId)&api-version=6.0-preview.1"
$ignore = Invoke-RestMethod -Method DELETE -Uri $url -ContentType "application/json" -Headers $header
}
}
DeleteLease "yourBuildDefinitionId"
Note :
The PAT token can be created from Azure Devops Portal using below
Sign in to your organization in Azure DevOps (https://dev.azure.com/{yourorganization})
From your home page, open your user settings, and then select Personal access tokens.
To get the build definition Id- see the URL of build , it will have the ID in the URL itself.
To fix that problem you can:
clone failed stage in the current release pipeline configuration
delete the original stage and use a clone instead of a deleted stage with a different name.
delete the previous failed release (*it will be possible)
after deleting you can rename the copied stage again.
enjoy
Go to the pipeline, and check retention for each run, and if found delete them.
This did solve my problem of deleting a pipeline.
You can also just temporarily choose to retain nothing, then delete what you want, then revert.
You just need to click on three dots menu button and select delete then it will make sure that you know what you are actually doing, check the "
Automatically cancel any in-progress release deployments" and remove it