如何在可从单元测试访问的 Azure DevOps 服务中传递/存储机密

How to pass / store secrets in Azure DevOps Services that can be accessed from unit test

我需要在从环境变量中检索到的单元测试执行中使用秘密密码。

测试由版本 2 中的 Visual Studio 测试任务执行。*

_networkCredential = new NetworkCredential(Environment.GetEnvironmentVariable("DomainAccountUsername"), Environment.GetEnvironmentVariable("DomainAccountPassword"));

如果我直接从 Powershell 设置 DomainAccountPassword,一切正常,测试成功结束,但我不想向团队中的其他用户显示密码。

Write-Host "##vso[task.setvariable variable=DomainAccountPassword;]MyExamplePassword"

传递在图书馆组中定义的秘密不起作用,导致身份验证错误。

Write-Host "##vso[task.setvariable variable=DomainAccountPassword;]$(secretPassword)"

如何将机密传递给 VSTS 任务,以便它可以在外部进行身份验证API?

谢谢!

根据Documentation

Secret variables are encrypted at rest with a 2048-bit RSA key. Secrets are available on the agent for tasks and scripts to use (so be careful about who has access to alter your pipeline).

...

Unlike a normal variable, they are not automatically decrypted into environment variables for scripts. You can explicitly map them in, though.

To pass a secret to a script, use the Environment section of the scripting task's input variables.

在脚本中使用秘密

将变量设置为机密:

将变量显式传递给脚本

并在脚本中按名称使用新环境变量 $env:topshelfPassword

如果您的管道是 YAML 而不是在经典编辑器中

You should not set secret variables in your YAML file. Instead, you should set them in the pipeline editor using the web interface. These variables are scoped to the pipeline in which you set them.

The following example shows how to pass a secret variable called mySecret set in the web interface to a script.

YAML

steps:

- powershell: |
    # Using an input-macro:
    Write-Host "This works: $(mySecret)"

    # Using the env var directly:
    Write-Host "This does not work: $env:MYSECRET"

    # Using the mapped env var:
    Write-Host "This works: $env:MY_MAPPED_ENV_VAR"    # Recommended
  env:
    MY_MAPPED_ENV_VAR: $(mySecret)

注意变量在网络中是如何声明的 ui mySecret 以及什么对典型的非秘密变量 ($env:mySecret) 有效 [=36= 】 这是秘密。然而,在 YAML 中起作用而在经典体验中不起作用(我相信我是正确的)是使用“输入宏”语法($(mySecret))。

似乎Visual Studio测试任务无法在运行时作为环境变量获取秘密,但它可以接受来自 TestContext 的秘密集作为参数

_networkCredential = new NetworkCredential(Environment.GetEnvironmentVariable("DomainAccountUsername"), TestContext.Parameters["DomainAccountPassword"]);

我已将 .runsettings 文件添加到测试项目

<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <TestRunParameters>
    <Parameter name="DomainAccountPassword" value="" />
  </TestRunParameters>
</RunSettings>

并且在 Visual Studio 测试任务选项中,我设置了设置文件的路径并用我的密码覆盖了 DomainAccountPassword 参数。

Visual Studio Test task options