简体   繁体   English

TFS 2015 API使用PowerShell从池中删除代理

[英]TFS 2015 API remove agent from pool with PowerShell

I'm working on removing an agent from a pool temporarily, install new software on the buildserver the agent is on, test that it works, and then add the agent to the pool again. 我正在临时从池中删除代理,在代理所在的构建服务器上安装新软件,测试其是否正常运行,然后将代理再次添加到池中。

I would like to do that programmatically, either with PowerShell or if that isn't a possibility, then do it with C#. 我想以编程方式执行此操作,或者使用PowerShell,或者如果不可能,请使用C#。

The problem is that I can't find any documentation that can assist me on doing this, either through the TFS REST API or through the tools that come with Visual Studio. 问题是,无论是通过TFS REST API还是通过Visual Studio附带的工具,我都找不到任何可以帮助我完成此工作的文档。

So I'm specifically asking: 所以我专门问:

How do I remove a named agent from a build pool and how do I add a named agent back into the build pool? 如何从构建池中删除命名代理,以及如何将命名代理重新添加到构建池中?

I basically want the same functionality of going onto the web administration of TFS and unchecking/checking an agent in the pool. 我基本上希望具有与TFS的Web管理以及取消/检查池中的代理程序相同的功能。

When I try to enable/disable an agent with the information provided by starain-msft, I get the following error: 当我尝试使用starain-msft提供的信息启用/禁用代理时,出现以下错误:

Invoke-RestMethod :
404 - File or directory not found.
Server Error

Later I removed much of the error, as I found out that issue lay in my company's proxy. 后来我消除了大部分错误,因为我发现问题出在我公司的代理中。 Read here: Azure DevOps Services REST API Reference 在这里阅读: Azure DevOps Services REST API参考

But I got it to work with the help of starain-msft. 但是我得到了starain-msft的帮助。

The final solution looks like this: 最终的解决方案如下所示:

Function TFSwebRequest {
    param
    (
        [ValidateNotNullOrEmpty()]
        [Parameter(Mandatory = $true)]
        [string] $Uri,

        [ValidateNotNullOrEmpty()]
        [Parameter(Mandatory = $true)]
        [string] $Method,

        [ValidateNotNullOrEmpty()]
        [string] $ContentType,

        [ValidateNotNullOrEmpty()]
        [string] $ContentBody,

        [ValidateNotNullOrEmpty()]
        [System.Net.WebHeaderCollection] $Headers
    )

    # Creating Webrequest from 'Uri'
    $webRequest = [System.Net.HttpWebRequest]::CreateHttp($Uri)

    $webRequest.UseDefaultCredentials = $true
    $webRequest.Method = $Method
    if ($Headers.Count -ne 0) {
        $webRequest.Headers = $Headers
    }
    if (![string]::IsNullOrEmpty($ContentType)) {
        $webRequest.ContentType = $ContentType
    }
    if (![string]::IsNullOrEmpty($ContentBody)) {
        $Body = [byte[]][char[]]$ContentBody
        $Stream = $webRequest.GetRequestStream();
        $Stream.Write($Body, 0, $Body.Length);
    }

    # Get webresponse to a variable
    try {
        [System.Net.WebResponse]$webResponse = $webRequest.GetResponse()
    }
    catch {
        $ErrorMessage = $_.Exception.Message
        Write-Host "TFSwebRequest Failed = " $ErrorMessage -ForegroundColor Red
    }

    # Stream webresponse to a string
    $webResponseStream = $webResponse.GetResponseStream()
    $streamReader = New-Object System.IO.StreamReader $webResponseStream
    $result = $streamReader.ReadToEnd() | ConvertFrom-Json

    return ,$result
}

$agentUri = "http://teamfoundation:8080/tfs/Main/_apis/distributedtask/pools/$($poolID)/agents/$($agentID)?api-version=2.3-preview.1"
$contentBody = @"
{
    "maxParallelism": 1,
    "id": INSERTID,
    "enabled": true #Or false
}
"@

$headers = New-Object System.Net.WebHeaderCollection
$headers.Add("X-HTTP-Method-Override", "PATCH")

TFSwebRequest -Uri $agentUri -Method "POST" -Headers $headers -ContentType "application/json" -ContentBody $contentBody

REST API of the agent pool and agent: 代理程序池和代理程序的REST API:

Get agent pools (request method: GET): 获取代理池(请求方法:GET):

http://[TFS URL]/_apis/distributedtask/pools?api-version=2.3-preview.1

Get agents of an agent pool (Request method: GET): 获取代理池的代理(请求方法:GET):

http://[TFS URL]/_apis/distributedtask/pools/[pool id]/agents?api-version=2.3-preview.1

Disable/enable build agent (Request method: PATCH) 禁用/启用构建代理(请求方法:PATCH)

http://[TFS URL]/_apis/distributedtask/pools/[pool id]/agents/[agent id]?api-version=2.3-preview.1

Body ( Content-Type: application/json ) Content-Type: application/jsonContent-Type: application/json

{
    "enabled": false,
    "id": [agent id],
    "maxParallelism": 1
}

Delete an agent from an agent pool (request method: DELETE): 从座席池中删除座席(请求方法:DELETE):

http://[Tfs URL]/_apis/distributedtask/pools/[pool id]/agents/[agent id]?api-version=2.3-preview.1

Simple sample to call REST API (PowerShell): 调用REST API(PowerShell)的简单示例:

Param(
   [string]$vstsAccount = "<VSTS-ACCOUNT-NAME>",
   [string]$projectName = "<PROJECT-NAME>",
   [string]$buildNumber = "<BUILD-NUMBER>",
   [string]$keepForever = "true",
   [string]$user = "",
   [string]$token = "<PERSONAL-ACCESS-TOKEN>"
)

# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))

$uri = "https://$($vstsAccount).visualstudio.com/DefaultCollection/$($projectName)/_apis/build/builds?api-version=2.0&buildNumber=$($buildNumber)"
$result = Invoke-RestMethod -Uri $uri -Method Get -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}

For details: Calling VSTS APIs with PowerShell 有关详细信息: 使用PowerShell调用VSTS API

C# code to call REST API: 调用REST API的C#代码:

String MyURI = "REST API URL";
WebRequest WReq = WebRequest.Create(MyURI);
WReq.Credentials =
    new NetworkCredential("[user name]", "[password]", "[domain]");

WebResponse response = WReq.GetResponse();
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
Stream dataStream = response.GetResponseStream();

StreamReader reader = new StreamReader(dataStream);

string responseFromServer = reader.ReadToEnd();

Console.WriteLine(responseFromServer);

On the other hand, you need to restart the build agent after you install new software to the agent machine in order to recognize them. 另一方面,在将新软件安装到代理计算机之后,您需要重新启动构建代理以识别它们。

There is no such API to create or remove an agent from the agent pool. 没有此类API可用于创建代理或从代理池中删除代理。 And it's not needed to write your own script. 而且不需要编写自己的脚本。 When you download the agent, you just need to run a command prompt as Administrator, and then run ConfigureAgent.cmd on your build agent machine: 下载代理程序时,您只需要以管理员身份运行命令提示符,然后在构建代理程序计算机上运行ConfigureAgent.cmd

C:\Agent\ConfigureAgent.cmd

Then respond to the prompts. 然后响应提示。 Check Deploy an agent on Windows for TFS 2015 选中在Windows上为TFS 2015部署代理

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 是否可以使用TFS 2015 API来查询来自TFS 2010的QueryHistory变更集? - Is it possible to use TFS 2015 api to QueryHistory changesets from TFS 2010? 如何在 TFS 2015 中增加测试代理的屏幕分辨率 - How to increase the screen resolution on Test Agent in TFS 2015 TFS 2015:版本定义REST API问题 - TFS 2015: Release Definition REST API Issue 使用TFS ExtendedClient API删除TFS GlobalList - Remove TFS GlobalList using TFS ExtendedClient API 是否有一个.NET API等同于TFS 2015的“Build 2.0”REST API? - Is there a .NET API equivalent to the “Build 2.0” REST API for TFS 2015? TFS 2015构建代理未将System。*。Http文件复制到放置位置 - System.*.Http files not copied to the drop location by TFS 2015 build-agent 为什么 TFS 2015 SP3 构建代理在添加 Microsoft.CodeAnalysis.NetAnalyzers 时会失败? - Why does TFS 2015 SP3 Build Agent fail when adding Microsoft.CodeAnalysis.NetAnalyzers? 如何使用REST API在TFS 2015中触发构建 - How to trigger a build in TFS 2015 using REST API 如何使用devop api在TFS 2015上检索所有“项目集合”的列表 - How to retrieve, with devops api on TFS 2015 the list of all the “project collections” TFS 2010 API:队列同步构建并获取每个排队构建的状态:“在代理上运行(等待构建代理)” - TFS 2010 API: Queue builds synchronously and get the state of each queued build: “Run On Agent (waiting for build agent)”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM