如何通过VSTS REST API创建构建定义 [英] How to create Build Definitions through VSTS REST API
问题描述
情况:
我目前正在通过bitbucket-> vsts-> azure来自动化CI / CD配置。
我的理想结果是能够将我的配置值粘贴(或手动输入)到各自的控制台程序中,并使应用程序配置整个CI / CD折磨,而不必单击所有Web界面。现在可以在Bitbucket和Azure中使用,但是事实证明通过REST API创建VSTS CI / CD配置非常困难。
Azure资源和Bitbucket配置是通过与REST API通讯的简单.NET控制台应用程序创建的。基本上复制粘贴(或手动输入)所有值(蓝色输入值 / bitbucket输入值)进入控制台应用程序,它将在5分钟内完成所有配置。
问题:
现在,我面临着尝试在VSTS中自动化构建配置和发布配置的难题。 VSTS客户端库的文档。
老实说,我对如何通过API或客户端库创建构建定义。
-
BuildHttpClient 有三种我可以使用的方法: / p>
公共虚拟任务< BuildDefinition> CreateDefinitionAsync(BuildDefinition definition,Guid project,int?definitionToCloneId = null,int?definitionToCloneRevision = null,object userState = null,CancellationToken cancelestToken = default(CancellationToken));;复制代码
公共虚拟Task< BuildDefinition> CreateDefinitionAsync(BuildDefinition definition,int?definitionToCloneId = null,int?definitionToCloneRevision = null,object userState = null,CancellationToken cancelestToken = default(CancellationToken));;
公共虚拟Task< BuildDefinition> CreateDefinitionAsync(BuildDefinition定义,字符串项目,int?definitionToCloneId = null,int?definitionToCloneRevision = null,对象userState = null,CancellationToken cancelleToken = default(CancellationToken));
-
BuildDefinition 具有以下属性。
命名空间Microsoft.TeamFoundation.Build.WebApi
{
[DataContract]
public class BuildDefinition:BuildDefinitionReference
{
public BuildDefinition();
公共列表< string>标签{get; }
public PropertiesCollection属性{get; }
public List< RetentionPolicy>保留规则{get; }
public List< Demand>需求{得到; }
public IDictionary< string,BuildDefinitionVariable>变量{get; }
public List< BuildTrigger>触发{ }
public ProcessParameters ProcessParameters {get;组; }
public BuildRepository储存库{get;组; }
public List< BuildOption>选项{get; }
public List< BuildDefinitionStep>步骤{ }
public bool BadgeEnabled {get;组; }
public int JobTimeoutInMinutes {get;组; }
public BuildAuthorizationScope JobAuthorizationScope {get;组; }
公共字符串DropLocation {get;组; }
公共字符串说明{get;组; }
public string评论{get;组; }
公用字串BuildNumberFormat {get;组; }
public Build LatestBuild {get; }
public Build LatestCompletedBuild {get; }
}
}
<如您所见,构建定义的最重要属性是只读的。
如何通过REST API创建构建定义?是否有VSTS更好的替代方法可以使我做到这一点?
REST API的格式为创建构建定义,如下所示:
POST https:// {account} .visualstudio.com / {project} / _apis / build / definitions?api-version = 5.0-preview.6
application / json示例:
{
process:{
phases:[
{
steps:[
],
name: Phase 1,
refName: Phase_1,
condition: succeeded(),
target:{
executionOptions:{
type:0
},
allowScriptsAuthAccessOption:false,
type:1
},
jobAuthorizationScope: projectCollection,
jobCancelTimeoutInMinutes:1
}
],
type:1
},
存储库:{
属性:{
cleanOptions: 0,
labelSources: 0,
labelSourcesFormat: $(build.buildNumber),
reportBuildStatus: true,
gitLfsSupport: false,
skipSyncSource: false,
checkoutNestedSubmodules : false,
fetchDepth: 0
},
id: 4ba24767-e5a6-4987-80cc-ebaeca01fdbc,
type : TfsGit,
名称: product1,
url: https://marinaliu.visualstudio.com/Git2/_git/product1,
defaultBranch : refs / heads / master,
clean: false,
checkoutSubmodules:false
},
processParameters:{},
草稿:[],
queue:{
id:324,
name: ownPC,
pool:{
id:23,
name: ownPC
}
},
name: definitionCreatedByRESTAPI,
type: build,
queueStatus:已启用
}
要使用C#中的REST API,您可以按以下方式进行转换:
var personalaccesstoken = PAT;
var base64Token = Convert.ToBase64String(Encoding.ASCII.GetBytes($:{personalaccesstoken})));
HttpClient客户端=新的HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( Basic,base64Token);
var requestMessage = new HttpRequestMessage(HttpMethod.Post, https://account.visualstudio.com/project/_apis/build/definitions?api-version=5.0-preview.6);
requestMessage.Content = new StringContent( {\ process\:{\ phases\:[{\ steps\:[],\ name\ :\ Phase 1\,\ refName\:\ Phase_1\,\ condition\:\ succeeded()\,\ target\ :{\ executionOptions\:{\typetype:0},\ allowScriptsAuthAccessOption\:false,\ type\:1},\ jobAuthorizationScope\ :\ projectCollection\,\ jobCancelTimeoutInMinutes\:1}],\ type\:1},rerepository\:{\ properties\: {\ cleanOptions\:\ 0\,\ labelSources\:\ 0\,\ labelSourcesFormat\:\ $(build.buildNumber) \,\ reportBuildStatus\:\ true\,\ gitLfsSupport\:\ false\,\ skipSyncSource\:\ false\ ,\ checkoutNestedSubmodules\:\ false\,\ fetchDepth\:\ 0\},\ id\:\ 4ba24767-e5a6- 4987-80cc-ebaeca01fdbc\,\ type\:\ TfsGit\,\ name\:\ product1\,\ url\:\ \ https://marinaliu.visualstudio.com/Git2/_git/product1\,\ defaultBranch\:\ refs / heads / master\,\ clean\:\ \\假\,\ checkoutSubmodules\:false},\ processParameters\:{},\ drafts\:[],\ queue\:{\ id\:324, \ name\:\ ownPC\,\ pool\:{\ id\:23,\ name\:\ ownPC\ }},\ name\:\ definitionCreatedByRESTAPI\,\ type\:\ build\,\ queueStatus\:\ enabled\ },Encoding.UTF8, application / json);
HttpResponseMessage响应= client.SendAsync(requestMessage).Result;
response.EnsureSuccessStatusCode();
通过引用博客为C#程序以编程方式访问TFS / VSTS 2017。
Situation:
I'm currently working on automating CI/CD configurations through bitbucket -> vsts -> azure.
My ideal result is to be able to copy paste (or manually enter) my configuration values into their respective console programs and have the applications configure the whole CI/CD ordeal without having to click through all the web interfaces. It's now possible in Bitbucket and Azure, but creating the VSTS CI/CD configurations through REST API is proving to be difficult.
Azure resources and Bitbucket configurations are currently created through a simple .NET console application that talks to the REST APIs. Basically copy paste (or manually enter) all the values (azure input values / bitbucket input values)into the console application and it will configure everything within 5 minutes.
Problem:
Now I face the harder part of trying to automate build configurations and release configurations in VSTS. Microsoft Docs isn't great on the documentation of VSTS client libraries.
I'm honestly at a loss for how I can create a build definition through the API or Client Library.
The BuildHttpClient has three methods I can work with:
public virtual Task<BuildDefinition> CreateDefinitionAsync(BuildDefinition definition, Guid project, int? definitionToCloneId = null, int? definitionToCloneRevision = null, object userState = null, CancellationToken cancellationToken = default(CancellationToken)); public virtual Task<BuildDefinition> CreateDefinitionAsync(BuildDefinition definition, int? definitionToCloneId = null, int? definitionToCloneRevision = null, object userState = null, CancellationToken cancellationToken = default(CancellationToken)); public virtual Task<BuildDefinition> CreateDefinitionAsync(BuildDefinition definition, string project, int? definitionToCloneId = null, int? definitionToCloneRevision = null, object userState = null, CancellationToken cancellationToken = default(CancellationToken));
The BuildDefinition has the following properties.
namespace Microsoft.TeamFoundation.Build.WebApi { [DataContract] public class BuildDefinition : BuildDefinitionReference { public BuildDefinition(); public List<string> Tags { get; } public PropertiesCollection Properties { get; } public List<RetentionPolicy> RetentionRules { get; } public List<Demand> Demands { get; } public IDictionary<string, BuildDefinitionVariable> Variables { get; } public List<BuildTrigger> Triggers { get; } public ProcessParameters ProcessParameters { get; set; } public BuildRepository Repository { get; set; } public List<BuildOption> Options { get; } public List<BuildDefinitionStep> Steps { get; } public bool BadgeEnabled { get; set; } public int JobTimeoutInMinutes { get; set; } public BuildAuthorizationScope JobAuthorizationScope { get; set; } public string DropLocation { get; set; } public string Description { get; set; } public string Comment { get; set; } public string BuildNumberFormat { get; set; } public Build LatestBuild { get; } public Build LatestCompletedBuild { get; } } }
As you can see, the most important properties of a build definition are read-only.
How do I go about creating a build definition through the REST API? Are there better alternatives to VSTS that will allow me to do this?
The format for the REST API to create a build definition as below:
POST https://{account}.visualstudio.com/{project}/_apis/build/definitions?api-version=5.0-preview.6
application/json example:
{
"process": {
"phases": [
{
"steps": [
],
"name": "Phase 1",
"refName": "Phase_1",
"condition": "succeeded()",
"target": {
"executionOptions": {
"type": 0
},
"allowScriptsAuthAccessOption": false,
"type": 1
},
"jobAuthorizationScope": "projectCollection",
"jobCancelTimeoutInMinutes": 1
}
],
"type": 1
},
"repository": {
"properties": {
"cleanOptions": "0",
"labelSources": "0",
"labelSourcesFormat": "$(build.buildNumber)",
"reportBuildStatus": "true",
"gitLfsSupport": "false",
"skipSyncSource": "false",
"checkoutNestedSubmodules": "false",
"fetchDepth": "0"
},
"id": "4ba24767-e5a6-4987-80cc-ebaeca01fdbc",
"type": "TfsGit",
"name": "product1",
"url": "https://marinaliu.visualstudio.com/Git2/_git/product1",
"defaultBranch": "refs/heads/master",
"clean": "false",
"checkoutSubmodules": false
},
"processParameters": {},
"drafts": [],
"queue": {
"id": 324,
"name": "ownPC",
"pool": {
"id": 23,
"name": "ownPC"
}
},
"name": "definitionCreatedByRESTAPI",
"type": "build",
"queueStatus": "enabled"
}
To use the REST API in C#, you can convert as below:
var personalaccesstoken = "PAT";
var base64Token = Convert.ToBase64String(Encoding.ASCII.GetBytes($":{personalaccesstoken}"));
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", base64Token);
var requestMessage = new HttpRequestMessage(HttpMethod.Post, "https://account.visualstudio.com/project/_apis/build/definitions?api-version=5.0-preview.6");
requestMessage.Content = new StringContent("{\"process\": { \"phases\": [{\"steps\": [], \"name\": \"Phase 1\",\"refName\": \"Phase_1\",\"condition\": \"succeeded()\",\"target\": { \"executionOptions\": { \"type\": 0 },\"allowScriptsAuthAccessOption\": false, \"type\": 1 }, \"jobAuthorizationScope\": \"projectCollection\", \"jobCancelTimeoutInMinutes\": 1 }],\"type\": 1 }, \"repository\": { \"properties\": { \"cleanOptions\": \"0\",\"labelSources\": \"0\",\"labelSourcesFormat\": \"$(build.buildNumber)\", \"reportBuildStatus\": \"true\",\"gitLfsSupport\": \"false\", \"skipSyncSource\": \"false\",\"checkoutNestedSubmodules\": \"false\", \"fetchDepth\": \"0\"},\"id\": \"4ba24767-e5a6-4987-80cc-ebaeca01fdbc\",\"type\": \"TfsGit\",\"name\": \"product1\", \"url\": \"https://marinaliu.visualstudio.com/Git2/_git/product1\", \"defaultBranch\": \"refs/heads/master\", \"clean\": \"false\",\"checkoutSubmodules\": false },\"processParameters\": {}, \"drafts\": [],\"queue\": { \"id\": 324, \"name\": \"ownPC\",\"pool\": {\"id\": 23, \"name\": \"ownPC\"}}, \"name\": \"definitionCreatedByRESTAPI\", \"type\": \"build\",\"queueStatus\": \"enabled\"}", Encoding.UTF8, "application/json");
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
response.EnsureSuccessStatusCode();
By referring the blog Accessing TFS/VSTS 2017 programmatically for the C# program.
这篇关于如何通过VSTS REST API创建构建定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!