【问题标题】:Read locked Azure DevOps variables from .Net Core applicatoin从 .Net Core 应用程序读取锁定的 Azure DevOps 变量
【发布时间】:2020-12-03 09:42:49
【问题描述】:

我在 Azure DevOps 中有一个发布管道,其中一个步骤是运行使用 Nunit 设计的测试。

任务的 YAML:

steps:
- task: DotNetCoreCLI@2
  displayName: 'Run Tests'
  inputs:
    command: custom
    projects: '**/a/Tests.dll'
    custom: vstest
    arguments: '--logger:"trx;LogFileName=test.trx" '

在我的测试设置中,我使用以下方法从环境变量中检索一些设置:

private static IConfiguration InitConfiguration()
{
  var config = new ConfigurationBuilder()
      .AddJsonFile("appsettings.json")
      .AddEnvironmentVariables()
      .Build();
  return config;
}

我还将环境变量的值存储在 Azure DevOps 变量组中。

当我的变量未锁定时一切正常,它们被成功检索并且测试运行正常。

但是,当我锁定秘密时,它们的值变为空,因此我的测试无法运行。

为了从我的应用程序中正确读取锁定的变量,我应该进行哪些更改。

【问题讨论】:

    标签: .net-core azure-devops azure-pipelines nunit


    【解决方案1】:

    默认情况下,变量会映射到环境变量中,但当您锁定它们时,实际上会将它们设为机密。并且要将秘密地图作为环境,您必须明确映射它们。采取look on this

    variables:
     GLOBAL_MYSECRET: $(mySecret) # this will not work because the secret variable needs to be mapped as env
     GLOBAL_MY_MAPPED_ENV_VAR: $(nonSecretVariable) # this works because it's not a secret.
    
    steps:
    
    - powershell: |
        Write-Host "Using an input-macro works: $(mySecret)"
        Write-Host "Using the env var directly does not work: $env:MYSECRET"
        Write-Host "Using a global secret var mapped in the pipeline does not work either: $env:GLOBAL_MYSECRET"
        Write-Host "Using a global non-secret var mapped in the pipeline works: $env:GLOBAL_MY_MAPPED_ENV_VAR" 
        Write-Host "Using the mapped env var for this task works and is recommended: $env:MY_MAPPED_ENV_VAR"
      env:
        MY_MAPPED_ENV_VAR: $(mySecret) # the recommended way to map to an env variable
    
    - bash: |
        echo "Using an input-macro works: $(mySecret)"
        echo "Using the env var directly does not work: $MYSECRET"
        echo "Using a global secret var mapped in the pipeline does not work either: $GLOBAL_MYSECRET"
        echo "Using a global non-secret var mapped in the pipeline works: $GLOBAL_MY_MAPPED_ENV_VAR" 
        echo "Using the mapped env var for this task works and is recommended: $MY_MAPPED_ENV_VAR"
      env:
        MY_MAPPED_ENV_VAR: $(mySecret) # the recommended way to map to an env variable
    

    因此,如果您想在一项任务中使用秘密,您需要添加如下内容:

    env:
        MY_MAPPED_ENV_VAR: $(mySecret) 
    

    您需要分别为每个秘密执行此操作。

    经典也是如此。您需要在此处映射它们:

    【讨论】:

    • 谢谢你的回答,非 YAML 任务呢?
    • 是一样的。您还需要映射它们。在上面的链接中有一个引用经典管道的选项卡。我还编辑了我的回复。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 2020-05-13
    相关资源
    最近更新 更多