如何通过 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 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)进入控制台应用程序,它将在 5 分钟内配置所有内容。
问题:
现在我面临着尝试在 VSTS 中自动生成配置和发布配置的困难部分。 Microsoft Docs 在 documentation of VSTS client libraries.
上表现不佳
老实说,我不知道如何 create a build definition 通过 API 或客户端库。
BuildHttpClient 有三种我可以使用的方法:
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));
BuildDefinition 具有以下属性。
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; }
}
}
如您所见,构建定义的最重要属性是只读的。
如何通过 REST API 创建构建定义?有没有比 VSTS 更好的替代品可以让我做到这一点?
REST API 到 create a build definition 的格式如下:
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
},
"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"
}
要在 C# 中使用 REST API,您可以按如下方式转换:
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();
情况:
我目前正致力于通过 bitbucket -> vsts -> azure 自动化 CI/CD 配置。
我的理想结果是能够将我的配置值复制粘贴(或手动输入)到它们各自的控制台程序中,并让应用程序配置整个 CI/CD 考验,而无需单击所有 Web 界面.现在可以在 Bitbucket 和 Azure 中使用,但通过 REST API 创建 VSTS CI/CD 配置被证明是困难的。
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)进入控制台应用程序,它将在 5 分钟内配置所有内容。
问题:
现在我面临着尝试在 VSTS 中自动生成配置和发布配置的困难部分。 Microsoft Docs 在 documentation of VSTS client libraries.
上表现不佳老实说,我不知道如何 create a build definition 通过 API 或客户端库。
BuildHttpClient 有三种我可以使用的方法:
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));
BuildDefinition 具有以下属性。
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; } } }
如您所见,构建定义的最重要属性是只读的。
如何通过 REST API 创建构建定义?有没有比 VSTS 更好的替代品可以让我做到这一点?
REST API 到 create a build definition 的格式如下:
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
},
"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"
}
要在 C# 中使用 REST API,您可以按如下方式转换:
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();