azure-devopsazure-devops-rest-apiazure-devops-self-hosted-agent

How to disable self-hosted agent in AzureDevOps pool via command-line


We have multiple self-hosted build agents in out AzureDevOps and I want to automate their maintenance. (things like Windows updates or VSbuild tools)

I want to disable the agent in the pool so it doesn't receive build tasks while updates are running.

Does anyone know how to do this via command line?


Solution

  • Does anyone know how to do this via command line?

    Instead of CMD, you can use Powershell.exe(Cmd.exe is not recommended for calling azure devops rest api) in your local machine to disable any self-hosted agent via this rest api:

    Patch https://dev.azure.com/{OrganizationName}/_apis/distributedtask/pools/{PoolID}/agents/{AgentID}?api-version=5.0
    

    Request Body:

    {
        "id":{AgentID},"enabled":false
    }
    

    Details:

    1. Go Organization settings=>Agent Pools=>Choose the pool that host your self-hosted agent=>Check the Agents tab and click one of your agent to see details. Then you can find PoolID and AgentID.

      enter image description here

    2. Now let's create a PAT to authenticate into Azure DevOps. Only Agent Pools's Read&Manage access is enough.

      enter image description here

    3. Assuming my organizationName is TestOrganization, then my final powershell script would be:

    (You can run it in Windows Powershell ISE)

    $token = "wjqtxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxtgiga"
    
    $url="https://dev.azure.com/TestOrganization/_apis/distributedtask/pools/10/agents/9?api-version=5.0"
    
    $token = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(":$($token)"))
    
    $JSON = @'
    {
        "id":9,"enabled":false
    }
    '@
    
    $response = Invoke-RestMethod -Uri $url -Headers @{Authorization = "Basic $token"} -Method Patch -ContentType application/json -Body $JSON
    write-host $response | ConvertTo-Json -Depth 100
    

    With the $token(Your PAT), PoolID and AgentID, you can easily control which agent to be enabled/disabled via the "enabled":xxx(true or false here). Note that you need to replace the agentID in both URL and Request body.