azure-devops - 如何在可从单元测试访问的 Azure DevOps 服务中传递/存储 secret

标签 azure-devops azure-pipelines vstest

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

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

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

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

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

传递库组中定义的 secret 不起作用,导致身份验证错误。

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

如何将 secret 传递给 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.

在脚本中使用 secret

将变量设置为 secret : enter image description here

将变量显式传递给脚本 enter image description here

并在脚本中按名称使用新的环境变量 $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)

注意变量是如何在 web ui 中声明为 mySecret 的,以及什么对典型的非 secret 变量 ($env:mySecret) 不起作用/c 这是一个 secret 。然而,在 YAML 中起作用而在经典体验中不起作用(我相信我是正确的)是使用“输入宏”语法($(mySecret))。

关于azure-devops - 如何在可从单元测试访问的 Azure DevOps 服务中传递/存储 secret ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57976426/

相关文章:

powershell - 生成失败时如何在Azure DevOps PR中创建注释?

azure - 如果 azure 管道中的任何任务失败,请删除 Azure 资源

tfs - 为什么 TFS 代理未发现 VSTEST 功能

.net-core - 测试未在 Azure Devops 编译的 aspnet core 3.0 测试项目上运行

Azure管道重新运行失败的任务(不是整个阶段)

c# - 无法读取数据驱动测试的 csv 文件的第一列。 Visual Studio 2017

git - TFS Git 创建 repo - "User must become compliant"

azure-devops - 如何从 Azure Devops Powershell YAML 获取输出

azure - 如何使用 Visual Studio Team Services 在单个服务上发布具有多个站点的 Azure 云服务项目?

azure-devops - 覆盖状态检查失败?