Denis Biondic
Denis Biondic

Reputation: 8201

Configuration management in builds without source controlled config transformations

Given a configuration named "Data:ConnectionString" in appsettings.json file (ASP.NET Core application), how do I override this in the build? By overriding it can either be that there is a step which changes the value in appsettings.json before compilation during build, or that I override the parameter when using "dotnet test", or something else.

More info:

I have a ASP.NET Core application with standard configuration in appsettings.json. I do not want any connection string or sensitive data checked in the source control.

I am building my application using Visual Studio Team Service (cloud TFS). There is a step where tests are executed, and I want these tests to run against a remote service for which I do not want to check in the credentials.

Upvotes: 0

Views: 157

Answers (3)

There are a number of extensions available on http://marketplace.visualstudio.com that will help you without any complicated ness.

https://marketplace.visualstudio.com/items?itemName=YodLabs.VariableTasks

I like the Variable Tasks Pack that comes with:

  • Set Variable Set a variable value and optionally apply a transformation to it.
  • Set Variables with Credential Sets the username/password from an existing service endpoint
  • Set Variable from JSON Extracts a value from JSON using JSONPath
  • Set Variable from XML Extracts a value from XML using XPath
  • Update Build Number Allows you to change a build number Increment Version Increments a semver version number

Super easy... You can also just search for "json" or "variable" to find other options...

Upvotes: 1

GlennSills
GlennSills

Reputation: 4187

You can set the an environmental variable ASPNETCORE_ENVIRONMENT in the build to something like "Test". Create an appsettings.json file named appsettings.Test.Json. Then when you are setting up your configuration in Startup.cs do something like...

          var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

When the environmental variable is set to TEST, you new appsettings file will be loaded and can set the connection string to whatever you want.

Upvotes: 0

J. Doe
J. Doe

Reputation: 2747

Most popular ways:

  • Use app secrets
  • Use scripts section in your project.json. You have 4 events - precompile, postcompile, prepublish, postpublish

Upvotes: 0

Related Questions