Azure DevOps管道环境变量始终为空

时间:2019-07-22 12:38:02

标签: azure-devops nuget xunit

我正在使用此ICollectionFixture设置

[CollectionDefinition("BaseCollection")]
public class Collection : ICollectionFixture<TestContext>
{ }

TestContext的设置如下:

    public TestContext()
    {
        var builder = new ConfigurationBuilder().
            SetBasePath(Environment.CurrentDirectory).
            AddJsonFile("local.settings.json", optional: true, reloadOnChange: true).
            AddEnvironmentVariables();

        Configuration = builder.Build();

        var serviceCollection = new ServiceCollection();
        var connectionString = 
            Configuration.GetConnectionString("MyDbContext") ?? 
            Configuration.GetValue<string>("Values:MyDbContext") ??
            Configuration.GetValue<string>("MyDbContext") ??
            Environment.GetEnvironmentVariable("MyDbContext");


        serviceCollection.AddDbContext<MyDbContext>(options => options.UseSqlServer(connectionString), ServiceLifetime.Transient);
        ServiceProvider = serviceCollection.BuildServiceProvider();
    }

Test类如下所示:

[Collection("BaseCollection")]
public class MyIntegrationTestClass
{
    private readonly MyDbContext context;

    public MyIntegrationTestClass(TestContext testContext)
    {
        this.context = testContext.ServiceProvider.GetService<MyDbContext>();
    }
}

我的Azure DevOps管道变量: Azure DevOps pipeline variables

请注意,我在YAML中执行以下步骤:

steps:
- script: echo Building with PR using ConnectionString '$(MyDbContext)'

结果是这样打印的:

echo Building with PR using ConnectionString '***'

我从中得出的结论是环境变量在管道中找到,但在TestContext中却找不到。

由于某种原因,环境变量始终为null,如果我使用local.settings.json,它可以正常工作。我的管道中唯一不起作用的步骤是测试部分(构建,还原,打包和发布工作正常)。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

我曾经遇到过同一个问题。当我将秘密变量传递给docker时,它失败,值= null。

这是由于您在YAML中使用秘密变量引起的。实际上,doc曾说过:

  

您不应在YAML文件中设置秘密变量。相反,你   应该使用Web界面在管道编辑器中进行设置。这些   变量的作用域仅限于您在其中进行设置的管道。

而且,在此文档中,您还可以看到Azure Devops建议将机密变量映射为环境变量。

enter image description here

这就是为什么您会收到null值的原因,在使用YAML和命令行时,需要首先将其映射为环境变量。否则服务器无法正确分析其值。

您可以参考此doc,将bash脚本更改为以下格式:

- script: echo $MYSECRET
  env:
    MySecret: $(Foo)

注意:Foo是秘密变量名称。

答案 1 :(得分:0)

我的问题是我正在DevOps中运行自托管代理,而解决方法只是重新启动构建代理。