如何使用自定义 Azure Devops 扩展 index.ts 中的连接服务?

Pat*_*lan 5 tfs azure typescript azure-devops azure-pipelines

我为 Azure Devops 编写了一个自定义扩展,其中包含自定义连接服务和构建任务。在通过管道可视化设计器配置任务时,我可以使用连接服务来选择服务,然后使用该服务使用 API 中的数据填充选项列表。

但是,当任务执行时,我如何使用所选的服务。我需要从index.ts 访问该服务。该服务告诉我端点和 API 密钥。

在index.ts中,我可以使用类似以下代码的内容来访问服务的Guid,但是我可以使用Guid来获取服务或其详细信息吗?

import tl = require('azure-pipelines-task-lib/task');
async function run() {
try {
    const serviceString: string = tl.getInput('TestService', true);
    if (serviceString == 'bad') {
        tl.setResult(tl.TaskResult.Failed, 'Bad input was given');
         return;
    } ...
Run Code Online (Sandbox Code Playgroud)

我已经进行了大量搜索和阅读(包括以下文章),但找不到任何示例。

https://learn.microsoft.com/en-us/azure/devops/extend/develop/add-build-task?view=azure-devops

https://learn.microsoft.com/en-us/azure/devops/extend/develop/service-endpoints?view=azure-devops

Jos*_*hua 2

诀窍是使用更多的函数azure-pipelines-task-lib/task(在你的例子中,tl):

如果您的自定义连接服务添加类型为 的身份验证方案ms.vss-endpoint.endpoint-auth-scheme-token,则id令牌输入的 将为apitoken,并且您需要添加的代码将如下所示:

const endpoint = tl.getEndpointUrl(serviceString, true);
// The second parameter here is the name of the associated input 
// value(s) of the specific authenticationSchemes type (more on that later).
const token = tl.getEndpointAuthorizationParameter(serviceString, "apitoken", false)
Run Code Online (Sandbox Code Playgroud)

我怎么知道这个?实验

其他身份验证类型

我目前的经验与过去其他人的经验相呼应: Azure DevOps 不能很好地与完全自定义的连接服务配合使用。它确实附带了一些覆盖大多数基地的功能。根据您使用的参数,为第二个参数传递的值会发生tl.getEndpointAuthorizationParameter变化:

ms.vss-endpoint.endpoint-auth-scheme-token

附带一个标准输入:

  1. apitoken

ms.vss-endpoint.endpoint-auth-scheme-basic

附带两个输入:

  1. username
  2. password

示例加建议

首先建议:为了使您的代码更清晰,请将您的serviceString变量重命名为connectedServiceId(或一些需要明确的变体,它代表您连接的服务的ID )。

import tl = require('azure-pipelines-task-lib/task');

async function run() {
    try {
        const connectedServiceId = tl.getInput('TestService', true);

        if (connectedServiceId == 'bad' || connectedServiceId == undefined) {
            tl.setResult(tl.TaskResult.Failed, 'Bad input was given');
            return;
        }

        const endpoint = tl.getEndpointUrl(connectedServiceId, true);
        const token = tl.getEndpointAuthorizationParameter(connectedServiceId, "apitoken", false)
    }
    finally {
        // Probably report some failure here, right?
    }
}
Run Code Online (Sandbox Code Playgroud)

此外,添加connectedServiceId == undefined检查可以connectedServiceId在以后的函数调用中安全使用。

我发现有用/创建的示例