如何使用Azure DevOps REST Api编写构建计划脚本? [英] How to script build schedule using Azure DevOps REST Api?

查看:90
本文介绍了如何使用Azure DevOps REST Api编写构建计划脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题是我其他问题的延续-

This question is continuation of my other question - How to schedule an on-premise Azure DevOps build to run every 5 minutes?

我不知道如何编写构建时间表的脚本.我应该使用什么API?

I cannot figure out how to script the schedule for a build. What API am I supposed to use?

编辑1

我想强调-我不想每5分钟将构建队列排队.我要编写构建时间表的脚本.因此,我在定义更新REST Api"上-

I want to emphasize - I do not want to queue the build myself every 5 minute. I want to script a schedule of the build. So, I am at the Definition Update REST Api - https://docs.microsoft.com/en-us/rest/api/azure/devops/build/definitions/update?view=azure-devops-rest-5.1 and still do not get it how to update the build definition's schedule. The advice to open Fiddler and reverse engineer the API makes me think this is not documented. Does it mean that whatever I implement based on the traffic analysis may be broken on the next release?

编辑2

使用建议的解决方案.这是我的代码,基于提供的答案.我不得不更改2件事:

Using the proposed solution works. Here is my code, based on the provided answer. I had to change 2 things:

  1. 主体应为标量对象,而不是数组.因此,我将$BuildDefinition而不是@($BuildDefinition)转换为json.
  2. 我使用Windows身份验证,因为我们有一个本地Azure DevOps服务器.
  1. The body should be a scalar object, not an array. So, I convert $BuildDefinition rather than @($BuildDefinition) to json.
  2. I use Windows authentication, because we have an on-premise Azure DevOps server.


$BuildDefinition | Add-Member triggers $triggers -Force

$json = ConvertTo-Json $BuildDefinition -Depth 99 

$Url = $BuildDefinition.url -replace '(.+)\?.+',"`$1?api-version=5.0"
Invoke-RestMethod -Uri $url -Method Put -Body $json -ContentType "application/json" -UseDefaultCredentials

但是,必须通过 LIST API .后者返回构建定义的简化版本,该版本不能用于更新它.

However, the build definition object must be obtain through the GET API, not the LIST API. The latter returns a reduced version of the build definition, which cannot be used to update it.

编辑3

使用完整的符号(即refs/heads/master而不是仅master)指定分支非常重要.使用后者似乎有效-创建了时间表,分支过滤器看起来正确,但是不起作用.问题在于GUI并未给出任何错误提示.

It is very important to specify the branch using the full notation, i.e. refs/heads/master instead of just master. Using the latter appears to work - the schedules are created, the branch filter looks correct, but it does not work. The problem is that the GUI does not give any indication something is wrong.

推荐答案

如果要使用REST API设置构建计划,则可以使用

If you mean setting the build schedule using REST API, then you can use Definitions - Update

通过UI设置时间表后,您还可以在浏览器中按F12键跟踪API.

You can also press F12 in browser to track the API when set the schedule from the UI.

返回您的要求:

如何安排本地Azure DevOps构建每5分钟运行一次?

How to schedule an on-premise Azure DevOps build to run every 5 minutes?

就像您提到的那样,当前本地Azure DevOps Server目前不支持YAML中的计划.而且,用于定义基于时间的构建触发器的UI不够灵活. 因此,我们无法实现内置功能那样的功能.

Just as you mentioned, currently On-premise Azure DevOps Server does not support schedules in the YAML. And the UI for defining time-based build triggers isn't flexible enough. So, we cannot achieve that like the built-in feature.

但是我们可以调用

However we can call the queue build REST API to queue the build every 5 minutes, we have two ways to do that:

  1. 编写脚本以调用队列构建REST API,然后运行它 定期在客户端计算机上,我们可以使用Windows Task进行设置 调度程序.为此,请参考下面的博客:

  1. Write a script to call the queue build REST API, then run it periodically on a client machine, we can set it with Windows Task Scheduler. Reference below blogs to do that:

每x- Windows Task Scheduler的分钟数

示例:

Param(
       [string]$collectionurl = "https://server/DefaultCollection",
       [string]$projectName = "ProjectName",
       [string]$BuildDefinitionId = "11",
       [string]$user = "username",
       [string]$token = "password/PAT"
    )

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

    function CreateJsonBody
    {

        $value = @"
      {
      "definition": {
        "id": $BuildDefinitionId
      }

    }
    "@

     return $value
    }

    $json = CreateJsonBody

    $uri = "$($collectionurl)/$($projectName)/_apis/build/builds?api-version=5.1"


    $EndTime = Get-Date
    while($true) {
        $EndTime = $EndTime.AddMinutes(5)

        ###Queue build###
        $result = Invoke-RestMethod -Uri $uri -Method Post -Body $json -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}


        Start-Sleep -Seconds $( [int]( New-TimeSpan -End $EndTime ).TotalSeconds )
    }


UPDATE1:

要在启用计划触发器的情况下更新构建定义,我们需要在请求主体中附加触发器属性.

To update the build definition with the schedule trigger enabled, we need to append the trigger attributes in the request body.

GET build definition by calling the REST API, use the response as the request body.

在响应请求正文中添加触发器属性:

Append the triggers attributes in the response request body:

"triggers": [
    {
        "schedules": [
            {
                "branchFilters": [
                    "+refs/heads/master"
                ],
                "timeZoneId": "UTC",
                "startHours": 5,
                "startMinutes": 20,
                "daysToBuild": 31,
                "scheduleJobId": "5e8e3663-2d1c-482e-bb4d-91f804755010",
                "scheduleOnlyWithChanges": true
            }
        ],
        "triggerType": "schedule"
    }
]

UPDATE2:

好吧,您可以使用以下PowerShell脚本通过更新构建定义来启用/更新构建计划触发器:

Well, you can use below PowerShell script to enable/update the build schedule trigger by updating the build definition:

Param(
   [string]$collectionurl = "https://server/DefaultCollection",
   [string]$project = "projectname",
   [string]$definitionid = "183",
   [string]$user = "username",
   [string]$token = "password/PAT"
)

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

$ErrorActionPreference = 'SilentlyContinue' 

#Get resonse of the build definition
$defurl = "$collectionurl/$project/_apis/build/definitions/$($definitionid)?api-version=5.1"            
$definition = Invoke-RestMethod -Uri $defurl -Method Get -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}

#Set trigger array


 $triggers =  ' 
        [{
            "schedules": [
                {
                    "branchFilters": [
                        "+refs/heads/master"
                    ],
                    "timeZoneId": "UTC",
                    "startHours": 9,
                    "startMinutes": 40,
                    "daysToBuild": 31,
                    "scheduleOnlyWithChanges": true
                }
            ],
            "triggerType": "schedule"
        }]'


 cls
#Add a trigger block to the response body

$definition | Add-Member -NotePropertyName "triggers" -NotePropertyValue (Convertfrom-Json $triggers) -Force

Remove-TypeData System.Array  # Remove the redundant ETS-supplied .Count and values property

#Convert the response body to Json
$json = @($definition) | ConvertTo-Json -Depth 99 

#Update build definition
$updatedef = Invoke-RestMethod  -Uri $defurl  -Method Put -Body $json -ContentType "application/json" -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)}

Write-Host ($updatedef.triggers | ConvertTo-Json -Depth 99)

这篇关于如何使用Azure DevOps REST Api编写构建计划脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆