用于自动化Azure DevOps管道的API



我想通过API调用自动执行Azure管道的排队,获取管道/构建/作业状态的信息,

  1. Azure Pipelines文档仅提及"调用HTTP Rest API"任务的"API":https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/utility/http-rest-api?view=vsts这可能会派上用场,但不是我想要的。

  2. 有一个"Azure DevOps服务REST API":https://learn.microsoft.com/en-us/rest/api/azure/devops/?view=azure-devops-rest-5.1但我在那里找不到任何关于"管道"的提及,所以这似乎也不是正确的做法。

    StackOverflow标签azure-devops-rest-api也只提到VSTS和TFS:

    Visual Studio团队服务REST API是一组允许管理Visual Studio团队Services帐户以及TFS 2015和2017服务器的API。

除了这两个结果,我只找到了这些结果的各种副本的其他版本或翻译,以及许多关于Azure的无关文档。

我只是用错词搜索了吗?


Azure DevOps管道是否有实际的API
是否有可用的API资源管理器
它有适合JavaScript、Ruby或PHP等语言的客户端吗?

似乎我不擅长谷歌搜索:

通过API触发Azure Pipelines构建并启动构建并通过VSTS Rest API传递变量(通过在StackOverflow上搜索[azure-pipelines] api找到(将我指向上面提到的Azure DevOps Services Rest API。

我也一直在致力于DevOps管道的自动化,并不断回到这里。其中一些信息似乎已经过时。到我写这篇文章的时候,我相信这篇在微软文档中的文章是最新的。我确实需要挠头才能让它工作,但最终得到了这个代码

public static async Task InitiatePipeline(CancellationToken cancellationToken = default)
{
using(HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var token = Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", AppSettings.DevOpsPAT)));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", token);
var repoGuid = "Put GUID Here"; // You can get GUID for repo from the URL when you select the rpo of interest under  Repos is Project Settings
var bodyJson = @"{
""parameters"": {
""parameterName"": ""parameterValue""
},
""variables"": {},
""resources"": {
""repositories"": {
""self"": {
""repository"": {
""id"": """ + repoGuid + @""",
""type"": ""azureReposGit""
},
""refName"": ""refs/heads/master""
}
}
}
}";
var bodyContent = new StringContent(bodyJson, Encoding.UTF8, "application/json");
var pipeLineId = 61; // Can get this from URL when you open the pipeline of interest in Azure DevOps
var response = await client.PostAsync($"https://dev.azure.com/ORG_NAME/PROJECT_NAME/_apis/pipelines/{pipeLineId}/runs?api-version=6.0-preview.1", bodyContent, cancellationToken);
response.EnsureSuccessStatusCode();
}
}

我也遇到了这些问题,最终制作了API的powershell包装器,然后将其包装到Azure DevOps管道模板中。我刚刚发布了它,供任何人使用。我希望任何找到这个线程的人都能发现这个模板很有用。

使用AzFunc4DevOps,这可以通过事件驱动的方式实现。在C#中。

例如,以下是当另一个构建成功时如何触发构建:

[FunctionName(nameof(TriggerBuildWhenAnotherBuildSucceeds))]
public static async Task Run(
[BuildStatusChangedTrigger
(
Project = "%TEAM_PROJECT_NAME%",
BuildDefinitionIds = "%BUILD_DEFINITION_ID%",
ToValue = "Completed"
)] 
BuildProxy build,
[BuildClient]
BuildHttpClient buildClient,
[BuildDefinition(Project = "%TEAM_PROJECT_NAME%", Id = "%NEXT_BUILD_DEFINITION_ID%")]
BuildDefinitionProxy nextbuildDefinition
)
{
await buildClient.QueueBuildAsync(new Build
{
Definition = nextbuildDefinition,
Project = nextbuildDefinition.Project
});
}

下面是更多的例子。

最新更新