5
votes

I have a Azure web job (.NET Core 2.2) that reads a couple of settings from configuration at startup like this:

var builder = new HostBuilder()
    .UseEnvironment(Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT"))
    .ConfigureWebJobs()
    .ConfigureAppConfiguration((hostContext, configApp) =>
    {
        configApp.AddEnvironmentVariables();
        configApp.AddJsonFile("appsettings.json", optional: false);
    })
    .ConfigureLogging((hostingContext, logging) =>
    {
        logging.AddConsole();

        var instrumentationKey = hostingContext.Configuration["APPINSIGHTS_INSTRUMENTATIONKEY"];
        if (!string.IsNullOrEmpty(instrumentationKey))
        {
            Console.Writeline(instrumentationKey); // <- this always outputs key from appsettings.json, not from Azure Settings
            logging.AddApplicationInsights(instrumentationKey);
        }
    })
    .UseConsoleLifetime();     

As you can see, appsettings.json file is supposed to have a APPINSIGHTS_INSTRUMENTATIONKEY key, and it's reading it fine in development environment.

Now, for production, I want to override this APPINSIGHTS_INSTRUMENTATIONKEY key, by adding a setting with the same key in Azure Application Settings web interface.

However, when I deploy my webjob to Azure, it still has the old app insights key from appsettings.json. In order to force my webjob to have the overridden key from Azure Application settings, I have to delete the app insights key from appsettings.json.

Is there a way for my webjob to use Azure Application settings without having to delete keys from appsettings.json ?

1

1 Answers

5
votes

The problem is that Azure App Settings get sent via environment variables; and, you are loading environment variables first, then overriding with appsettings.json:

.ConfigureAppConfiguration((hostContext, configApp) =>
    {
        configApp.AddEnvironmentVariables();
        configApp.AddJsonFile("appsettings.json", optional: false);
    })

Reverse this to

.ConfigureAppConfiguration((hostContext, configApp) =>
    {
        configApp.AddJsonFile("appsettings.json", optional: false);
        configApp.AddEnvironmentVariables();
    })

And it will load your appsettings.json first, then override with environment variables.