Search code examples
azure-devopsazure-pipelinesazure-devops-rest-api

How to update Azure build definition agent from vs2017-win2016 to windows-2019 programmatically


I am trying to programatically update all my build pipeline agents from vs2017-win2016 to windows-2019. I have access to AZ CLI, PowerShell and REST API but I haven't found the magic incantation to make it work. Specifically I would like to update the Azure Pipeline agent for a specific project and build definition name.


Solution

  • How to update Azure build definition agent from vs2017-win2016 to windows-2019 programmatically

    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 build pipeline:

    PUT https://dev.azure.com/{organization}/{project}/_apis/build/definitions/{definitionId}?api-version=5.0
    

    Following is my test inline powershell scripts:

    $url = "https://dev.azure.com/{organization}/{project}/_apis/build/definitions/57?api-version=5.0"
    
    Write-Host "URL: $url"
    $pipeline = Invoke-RestMethod -Uri $url -Headers @{
        Authorization = "Bearer $env:SYSTEM_ACCESSTOKEN"
    }
    Write-Host "Pipeline = $($pipeline | ConvertTo-Json -Depth 100)"
    
    # Update an existing build definition named and build definition agent to its new value 2
    $pipeline.process.target.agentSpecification.identifier= "windows-2019"
    $pipeline.name= "UpdateVariabletest"
    
    ####****************** 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 build definition named and build definition agent is updated to" 
    
    $updatedef.process.target.agentSpecification.identifier
    $updatedef.name
    

    You could check the similar thread for some more details.